Differences
-
undefined
indicates that a variable has been declared but not been assigned to any value, including null
.
let foo;
console.log(foo);
null
is used to indicate that a variable doesn't have a value.
let foo = null;
console.log(foo);
-
undefined
and null
are considered to be different types.
undefined
is a type itself, whereas null
is a special value of object.
console.log(typeof undefined);
console.log(typeof null);
Since they are different types, here are the result of
equality and identity operators when comparing them to each other:
null == undefined;
null === undefined;
Good to know
JSON.stringify
omits undefined
, but keeps null
:
JSON.stringify({
name: 'John',
address: null,
age: undefined,
});