To check if a variable is undefined in JavaScript, you can use the typeof
operator. This operator returns the data type of the value stored in the variable. If the variable has been declared but has not been assigned a value, the typeof
operator will return undefined
.
Here is an example:
let myVariable;
console.log(typeof myVariable); // Output: "undefined"
Another way to check if a variable is undefined is to use the undefined
keyword. This keyword is a special global variable in JavaScript that holds the value undefined
. You can compare the value of a variable with the undefined
keyword using the strict equality operator (===
).
Here is an example:
let myVariable;
console.log(myVariable === undefined); // Output: true
A third way to check if a variable is undefined is to use the typeof
operator in combination with the !
operator, which negates the result of the typeof
operator. This will return true
if the variable is not defined, and false
if it is defined.
Here is an example:
let myVariable;
console.log(!typeof myVariable); // Output: true
In terms of safety, using the strict equality operator (===
) with the undefined
keyword is considered the safest way to check if a variable is undefined. This is because the typeof
operator can sometimes return unexpected results for certain data types, such as arrays and null values. Using the strict equality operator ensures that only the undefined
value will return true
when compared with the undefined
keyword.
Here is an example:
let myVariable;
console.log(myVariable === undefined); // Output: true
Helper function
To create a helper function to check if a value is undefined, you can use the strict equality operator (===
) with the undefined
keyword. The function should take a value as an argument and return true
if the value is undefined, and false
if it is not.
Here is an example of such a function:
function isUndefined(value) {
return value === undefined;
}
You can then use this function to check if a value is undefined like this:
let myVariable;
console.log(isUndefined(myVariable)); // Output: true