undefined means no value was given, and it is JavaScript's default. null means "empty", and a developer sets it on purpose.
JavaScript gives you undefined automatically in these cases:
- a variable that was declared but not given a value
- an object property that does not exist
- a function argument that the caller did not pass
- the result of a function with no
return
You write null yourself to say "there is no object here", for example let selectedUser = null before the user picks anyone.
They are different types. typeof undefined is 'undefined'. typeof null is 'object', because of an old bug that was never fixed.
They are loosely equal: null == undefined is true. They are not strictly equal: null === undefined is false. So x == null is a common short way to check for both at once.
Some features treat them the same and some do not:
??and?.treat both as missing.- Default parameters are used only for
undefined, not fornull. JSON.stringifydrops properties whose value isundefined, but keepsnull.
undefinedis JavaScript's default when nothing was assigned or something is missing.nullis set on purpose by a developer to mean "empty".typeof null === 'object'is an old bug that was kept.null == undefinedis true, butnull === undefinedis false.- Default parameters apply only for
undefined.JSON.stringifydropsundefinedbut keepsnull.
Read more