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