javascript check if is undefined
Here are some ways to check if a variable is `undefined` in JavaScript:
**Method 1: Using the `===` operator**
javascript
const foo = undefined;
if (foo === undefined) {
console.log("Foo is undefined");
}
**Method 2: Using the `==` operator**
Note that using `==` will check for equality with both `undefined` and `null`, so be careful!
javascript
const foo = undefined;
if (foo == undefined) {
console.log("Foo is undefined or null");
}
**Method 3: Using the `typeof` operator**
This method checks if the variable's type is indeed `undefined`.
javascript
const foo = undefined;
if (typeof foo === "undefined") {
console.log("Foo is undefined");
}
**Method 4: Using a simple equality check with an optional chaining operator (`?.`)**
If you're using a modern JavaScript version that supports optional chaining, this method can be more concise.
javascript
const foo = undefined;
if (foo?.toString() === "undefined") {
console.log("Foo is undefined");
}
**Method 5: Using a simple equality check with a nullish coalescing operator (`??`)**
Similar to the optional chaining method, this one uses the nullish coalescing operator to provide a default value if `foo` is `undefined` or `null`.
javascript
const foo = undefined;
if (foo ?? false) {
console.log("Foo is defined");
} else {
console.log("Foo is undefined");
}
All of these methods will check if a variable is indeed `undefined`, but keep in mind that some might also return `true` for other edge cases, such as
`null`. Choose the one that best fits your needs!