JS: undefined
What is undefined
undefined is the value of the property key "undefined" of
the Global Object.
console.assert((Object.hasOwn(globalThis, "undefined")) === true); console.assert(globalThis["undefined"] === undefined);
undefined is a literal value. For example, you can write let x = undefined;
Type of undefined
Type of undefined is "undefined", and it is the only value of the type.
console.assert(typeof undefined === "undefined");
Purpose of undefined
undefined is the value when:
- Variable doesn't have a value (not initialized). 〔see let Declaration〕
- Accessing a non-existent property. 〔see Get Set Property〕
- Accessing array element with index out of bound, or non-existent element in a Sparse Array.
- When function argument is not given. 〔see Function Parameters〕
- Return value of a function call when the function doesn't have
returnstatement, or emptyreturnstatement. - other similar cases.
let xx; console.assert(xx === undefined);
// accessing non-existent property return undefined console.assert({ "kk": 3 }.kk === 3); console.assert({ "kk": 3 }.xx === undefined);
// accessing out-of-bound array element returns undefined console.assert([1, 2][9] === undefined);
// When function argument is not given, value is undefined function ff(x) { return x; } console.assert(ff() === undefined);
// undefined is the return value of a function call when the function doesn't have return statement function ff() {} console.assert(ff() === undefined);
// undefined is the return value of a function with empty return statement function ff() { return; } console.assert(ff() === undefined);