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.
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.
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")}
Free Resources