😄 This post is based on the content from coding.courses.
Definition and Usage
The undefined value is the initial value automatically assigned by the JavaScript engine to indicate that a variable has not been assigned a value.
In other words, before a value is assigned to a variable, the JavaScript engine assigns undefined as the variable's initial value.
Therefore, referencing a variable after it has been declared but before a value is assigned returns undefined. However, if a value is assigned to the variable, the assigned value is returned instead of undefined.
# undefined in Regular Variables
let x;
console.log(x); // undefined
Assigning a value returns the assigned value.
let x;
console.log(x); // undefined
/* Assigning a value returns the assigned value. */
x = 1;
console.log(x); // 1
# undefined in Functions
In JavaScript, functions can also be treated as values.
If a function does not return a value using the return keyword after execution, it returns undefined.
If a value is returned using the return keyword, that value is returned.
function x(a, b) {
a + b; // No value returned via the return keyword
}
console.log(x(1, 2)); // undefined
function y(a, b) {
return a + b; // A value is returned via the return keyword
}
console.log(y(1, 2)); // 3
# undefined in Objects
Referencing a non-existent property on an object also returns undefined.
const obj = {};
console.log(obj.prop); // undefined
Creating a property and assigning a value returns the assigned value.
const obj = {};
console.log(obj.prop); // undefined
/* Create a property and assign a value */
obj.prop = 1;
console.log(obj.prop); // 1
# undefined in Arrays
Referencing a non-existent element on an array also returns undefined.
let arr = [];
console.log(arr[0]); // undefined
Assigning a value to the array returns the assigned value.
let arr = [];
console.log(arr[0]); // undefined
/* Assign a value to the array */
arr[0] = 1;
console.log(arr[0]); // 1
# Data Type of undefined
The data type of the undefined value is Undefined.
In JavaScript, you can check the data type of a variable using the typeof operator.
let x;
console.log(typeof x); // "undefined"
This means that undefined is a value with a unique data type.
# Evaluating undefined in Conditional Statements
The following example shows how the undefined value is evaluated in a conditional statement.
let x;
if (x === undefined) {
console.log("Evaluates to true.");
} else {
console.log("Evaluates to false.");
}
// Output: "Evaluates to true."
However, when the undefined value is evaluated as the boolean type, it is false.
let x;
if (x) {
console.log("Evaluates to true.");
} else {
console.log("Evaluates to false.");
}
// Output: "Evaluates to false."
// Evaluate using the Boolean() function
console.log(Boolean(x)); // false
Top comments (0)