JavaScript

How to check if a variable is undefined or null in JavaScript

Undefined variable. This is an error message that indicates that a variable inside a JavaScript code is declared but has no value. This is a very common mistake. There are a few simple methods in JavaScript to check or determine if a variable is undefined or null.
 

Use “null” with the operator “==”

You can use the equality operator (==) in JavaScript to check whether a variable is undefined or null. For example :

var str;

if (str == null) 
{
    alert('str variable is null!');
}

Output:

str variable is null!
 

Use the “undefined” type

In some cases, you can use the “undefined” keyword to check if a given variable is undefined. For example :

var str;

if (str == undefined) 
{
    alert('The str variable is undefined!');
}

Output:

The str variable is undefined!

Remember that a variable with an empty value is neither undefined nor null.

var str = '';
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *