DEV Community

Differences between "null" and "undefined" keywords?

Nuno Pereira on August 29, 2019

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 pl...
Collapse
 
jamesthomson profile image
James Thomson • Edited

Null and undefined are both primitives and falsy values. However null is also an object.

And this is why no one will ever fully understand JavaScript 😆

Even taken from MDN:

The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values.

And when you click through to primitive values, MDN states:

In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods.

Yet, typeof null // object 🤔

What the what 🤯

Collapse
 
vlasales profile image
Vlastimil Pospichal • Edited
anna = {}
bill = {}

anna.age = null
bill.age = null
console.log(anna.age == bill.age)  // ???
console.log(anna.age === bill.age)  // ???

anna.age = NaN
bill.age = NaN
console.log(anna.age == bill.age)  // ???
console.log(anna.age === bill.age)  // ???
Collapse
 
emptyother profile image
emptyother

The new optional parameter for ES6 only cares about undefined.

function myFunc(a, b = 0) { console.log(a,b); }
myFunc(1); // 1 0
myFunc(1,null); // 1 null
myFunc(1,undefined); // 1 0
myFunc(1,getSomeNonExistingValue()); // 1 (null or 0)

Wouldn't it be simpler to use undefined instead of null everywhere? Just stop using null?

Collapse
 
alexparra profile image
Alex Parra

Yeah, this has tripped me a couple of times...

Collapse
 
_ezell_ profile image
Ezell Frazier

I like to think of undefined as the void personified.

Collapse
 
umezvictor profile image
Victor Umezuruike

Sometimes it can be really confusing. Thanks for the explanation

Collapse
 
nitinreddy3 profile image
Nitin Reddy

Yeah, JavaScript is a weird programming language but a nice one.

Collapse
 
nunocpnp profile image
Nuno Pereira

Indeed :)

Collapse
 
nunocpnp profile image
Nuno Pereira

Cool, thx for adding this up !