In JavaScript, undefined
and null
don’t mean the same thing. This article aims to explain the real meaning with examples. Hope you find it useful.
What is null?
null
is a falsy assignment value. You as a programmer may want to assign the value null
to a variable. It simply means the value is blank or non-existent.
let name= null;
console.log(name); // prints, null
Interestingly, when we use typeof
to check the type of null, it returns "object".
typeof(null); // prints, "object"
Note: This can be confusing as null
is a primitive value. This is a bug in the language but has not been corrected even after series of updates to the language
What is undefined?
undefined
typically means a variable has been declared but has not yet been assigned a value.It is also a falsy value.
let name;
console.log(name); // prints, undefined
In the above example, we have declared a variable name
but haven't assigned a value to it. Hence the variable name
is undefined
.
There is also a way to confirm it,
typeof(name); // prints "undefined"
When you access non-existent object properties, you get an undefined
.
let information= {'name': 'James..'};console.log(information.name); // prints, "James"
console.log(information.address); // prints, undefined
ReferenceError
In the case of undefined
, the variable must be declared. On the contrary, accessing a variable that's not been declared will cause a ReferenceError
.
console.log(Zuri);
If you haven’t declared zuri variable and trying to access it like shown above, you will get an error,
In Summary
To summarize,
undefined
andnull
are primitive values and they represent falsy values.undefined
value is typically set by the JavaScript engine when a variable is declared but not assigned with any values.null
value is typically set by programmers when they want to assign an empty/blank value.- If you try to access the value of a variable that is not even declared, it will result in a
ReferenceError
.