Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

undefined
variable
check

How to check for undefined in JavaScript

Educative Answers Team

Programming involves the use of a lot of variables and objects which have several methods associated with them. Most of the variables/objects in use have to be manually initialized to a certain value since they do not receive default values at declaration.

The variable/object must hold a value in order for its associated methods to be used. Hence, it is good pra​ctice to check if the respective variable/object holds a value or if it is undefined.

svg viewer

JavaScript has undefined as a built-in keyword to check whether or not the variable/object is undefined. See the syntax of the statement below:

if (my_var === undefined) {
 // code in case my_var is undefined
} else {
 // code in case my_var has a value
} 

The === operator is used instead of == when checking for undefined variables/objects.

Code

The code snippet below illustrates how to check if a variable is undefined in JavaScript:

let my_var_1;
let my_var_2 = 10;

if (my_var_1 === undefined) {
    console.log("my_var_1 is undefined")
} else {
    console.log("my_var_1 holds some value")
}

if (my_var_2 === undefined) {
    console.log("my_var_2 is undefined")
} else {
    console.log("my_var_2 holds some value")
}

RELATED TAGS

undefined
variable
check
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring