They both represent a empty value.
Difference nr 1!
When you define a variable but not assign a value to it, it automatically puts a placeholder which is called undefined so you don't have do it manually, JavaScript does it for you.
Null means an empty or non-existent value.
Null is assigned, and explicitly means nothing. while undefined typically means a variable has been declared but not defined yet.
var a;
console.log(a);
// undefined
var b = null;
console.log(b);
// null
Difference nr 2!
Null and undefined are both primitives and falsy values. However null is also an object. Interestingly, this was actually an error in the original JavaScript implementation.
var a;
console.log(typeof(a));
// undefined
var b = null;
console.log(typeof(b));
// object
Difference nr 3!
As you can see so far, null and undefined are different, but share some similarities. Thus, it makes sense that null does not strictly equal undefined.
console.log(null !== undefined);
// true
But, and this may surprise you, null loosely equals undefined.
console.log(null == undefined);
// true
In JavaScript, a double equals tests for loose equality and preforms type coercion. This means we compare two values after converting them to a common type.
See you soon for more tips !
Top comments (9)
And this is why no one will ever fully understand JavaScript 😆
Even taken from MDN:
And when you click through to primitive values, MDN states:
Yet,
typeof null // object
🤔What the what 🤯
The new optional parameter for ES6 only cares about
undefined
.Wouldn't it be simpler to use
undefined
instead ofnull
everywhere? Just stop usingnull
?Yeah, this has tripped me a couple of times...
I like to think of undefined as the void personified.
Sometimes it can be really confusing. Thanks for the explanation
Yeah, JavaScript is a weird programming language but a nice one.
Indeed :)
Cool, thx for adding this up !