undefined and null
suggest changeAt first glance it may appear that null and undefined are basically the same, however there are subtle but important differences.
undefined is the value of a binding that has not been assigned one.
undefinedis a global value that represents the absence of an assigned value.typeof undefined === 'undefined'nullis a primitive, not an object. It is used when a value was explicitly assigned “no value”.typeof null === 'object'is a long-standing language quirk.
Setting a variable to undefined does not remove the binding. JSON.stringify omits object properties whose values are undefined, and it keeps properties whose values are null.
The following evaluate to undefined:
-
A variable when it is declared but not assigned a value
let foo; console.log('is undefined?', foo === undefined); // is undefined? true -
Accessing the value of a property that doesn’t exist
const foo = { a: 'a' }; console.log('is undefined?', foo.b === undefined); // is undefined? true -
The return value of a function that doesn’t return a value
function foo() { return; } console.log('is undefined?', foo() === undefined); // is undefined? true -
The value of a function argument that is declared but has been omitted from the function call
function foo(param) { console.log('is undefined?', param === undefined); } foo('a'); foo(); // is undefined? false // is undefined? true
undefined is also a property of the global window object.
// Only in browsers
console.log(window.undefined); // undefined
window.hasOwnProperty('undefined'); // true
Before ECMAScript 5 you could change the value of the window.undefined property. Since ES5 that global property is read-only. A local binding can still shadow undefined.