I want to know what the difference is between null
and undefined
in JavaScript.
I want to add a very subtle difference between null
and undefined
which is good to know when you are trying to learn Vanilla JavaScript(JS) from ground up:
null
is a reserved keyword in JS while undefined
is a variable
on the global object of the run-time environment you're in.While writing code, this difference is not identifiable as both null
and undefined
are always used in RHS of a JavaScript statement. But when you use them in LHS of an expression then you can observe this difference easily. So JS interpreter interprets the below code as error:
var null = 'foo'
It gives below error:
Uncaught SyntaxError: Unexpected token null
While below code runs successfully although I won't recommend doing so in real life:
var undefined = 'bar'
This works because undefined
is a variable on the global object (browser window object in case of client-side JS)