The difference between null and undefined in JavaScript
null
and undefined
may seem to be the same value, but they actually have subtle differences in JavaScript.
JavaScript primitive values
In JavaScript, there are six primitive values. Both null and undefined are two of them. The primitive values are:
- Boolean
- Null
- Undefined
- Number
- String
- Symbol
All other values besides these are objects (objects, functions, arrays, etc.).
Falsy values
In JavaScript, there are six falsy values. Both null and undefined are two of the six. The list of falsy values are:
- false
- 0 (zero)
- "" (empty string)
- null
- undefined
- NaN (Not A Number)
All other values in JavaScript are considered truthy.
What is null?
null is an empty or non-existent value. It literally means nothing.
const a = null;
console.log(a); // null
Null must be assigned. If const a
was not assigned to null, it would be undefined
and not null
when we console.log()
it.
What is undefined?
Undefined usually means that a variable has been declared, but not defined.
let b;
console.log(b); // undefined
We can also declare a variable to be undefined.
let c = undefined;
console.log(c); // undefined
If we try looking up the non-existent properties in an object, we will receive undefined.
const user = {};
console.log(user.name); // undefined
Equality checks
null
does not strictly equal undefined
because they are not of the same type. As we saw above, they are two different types of primitive values in JavaScript.
console.log(null !== undefined); // false
However, null
loosely equals undefined
.
console.log(null == undefined); // true
Triple Equals
Triple equals ===
tests for strict equality. This means that both the type and the value that we are comparing have to be the same.
Double Equals
Double equals ==
tests for loose equality and preforms type coercion. It compares two values after converting them to a common type.
Function parameters
Consider the following function that prints out the name that is passed to it as a parameter.
function sayHello(name = 'John') {
console.log(`Hi ${name}!`);
}
Passing undefined
will cause the function to use the default value of the parameter.
sayHello(undefined); // Hi John!
Passing null
will not make use the default value of the parameter.
sayHello(null); // Hi null!