How can I determine if a variable is 'undefined' or 'null'?

You can determine if a variable is undefined or null using simple conditional checks. Here's how you can do it with examples:

    Checking for undefined: You can use the typeof operator to check if a variable is undefined.

javascript

let variable1;  // variable1 is undefined
let variable2 = "Hello";  // variable2 is defined

if (typeof variable1 === "undefined") {
  console.log("variable1 is undefined");
} else {
  console.log("variable1 is defined");
}

if (typeof variable2 === "undefined") {
  console.log("variable2 is undefined");
} else {
  console.log("variable2 is defined");
}

    Checking for null: You can directly compare the variable with null to check if it's null.

javascript

let variable3 = null;  // variable3 is null
let variable4 = "World";  // variable4 is defined

if (variable3 === null) {
  console.log("variable3 is null");
} else {
  console.log("variable3 is not null");
}

if (variable4 === null) {
  console.log("variable4 is null");
} else {
  console.log("variable4 is not null");
}

In these examples, the typeof operator is used to check for undefined, and direct comparison (===) is used to check for null. It's important to differentiate between these two checks, as null is a specific value that represents the absence of a value, while undefined indicates that a variable has been declared but hasn't been assigned a value.

Comments