- undefined — the default primitive value of declared variables that have not yet been assigned a value (either in the code or during the creation phase of the execution context)
- null — an assigned primitive value (by someone) to indicate an empty value // never a default value
In other words, undefined simply means that the value of the variable hasn’t been defined yet (and we don’t know if it will ever be).
There are at least 8 ways to get
- A declared variable without assigning any value to it.
- Default return of functions that lack return statements.
- Return statements that do not explicitly return anything.
- Result of looking up non-existent properties in an object.
- Function parameters that have not passed.
- Any variable that has been intentionally set as
- Using the
- The value of the global variable
undefined(it is a property of the global object).
On the other hand, null means that the value is empty or lacks a value that has been intentionally set by a programmer. The machine does not set variables to
null for you. It is a purposed primitive.
typeof null; // "object" (not "null" for legacy reasons)
typeof undefined; // "undefined"
null === undefined; // false
null == undefined; // true
null === null; // true
null == null; // true
!null; // true
isNaN(1 + null) // false
isNaN(1 + undefined) // true
- MDN docs — null
- MDN docs — undefined