Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 19, 2024 › #HowTo #Javascript

How to Determine If Variable is Undefined or NULL in JavaScript

In JavaScript, it's essential to know if a variable is undefined or null to handle it appropriately in your code. Here are two methods to achieve this.

Method 1: Using the typeof Operator #

The typeof operator in JavaScript can be used to determine if a variable is undefined or null. It returns a string that represents the data type of the variable.

When applied to an undefined variable or a variable with a value of null, the typeof operator will return different strings for each case, allowing us to differentiate between the two.

  1. We define a function checkUndefinedOrNull that takes a variable as its parameter.
  2. Inside the function, we use an if-else if-else statement to check the type of the variable using the typeof operator.
  3. If the variable is found to be undefined, we log a message indicating that the variable is undefined.
  4. If the variable is equal to null, we log a message indicating that the variable is null.
  5. Otherwise, if the variable has a value, we log a message indicating that the variable has a value.

save
listen
AI Answer
Write Your Answer
loading
back
View All