| by Arround The Web | No comments

JavaScript Check if Variable Exists (Defined/Initialized)

While coding, it is sometimes necessary to check a variable’s existence to trigger a specific functionality. Suppose a developer wants to provide default values for a variable. In that case, they can check if the variable has been defined or initialized and set it to the desired default value. Also, checking if a variable exists can help the developers to identify bugs in the code.

This tutorial will demonstrate the way to identify whether the variable exists and is defined/initialized or not.

How to Check/Verify if a Variable Exists (Defined/Initialized) in JavaScript?

To determine if a variable is defined or initialized in JavaScript, use the “typeof” operator. The typeof operator that outputs a string signifies the type of the given operand. If the operand is a variable that is not defined/initialized, the typeof operator returns “undefined”.

Syntax

Use the given syntax for verifying the variable exists (defined/initialized):

typeof variable !== 'undefined'

Example

Create a variable “x” and assign a value “11”:

var x = 11;

Now, verify the variable “x”, and variable “y” are defined/initialized or not. To do so, check the variable’s type is not equivalent to the “undefined” using the “typeof” operator:

if(typeof x !== 'undefined'){
 console.log("Variable x is defined");
}
if(typeof y !== 'undefined'){
 console.log("Variable y is defined");
}

The output shows that the variable “x” is defined while the “y” is not, because as the typeof operator returns “undefined”:

You can also check without “typeof” operator, but it will throw an exceptional error. In contrast, the typeof operator does not throw/give a reference error if the variable is not declared/initialized:

if(x !== 'undefined'){
 console.log("Variable x is defined");
}
if(y !== 'undefined'){
 console.log("Variable y is defined");
}

It produces an exceptional error on the variable “y” which is not declared/initialized:

We have provided all the essential instructions relevant to verify the variable declared/initialized in JavaScript.

Conclusion

To determine whether the variable exists (defined/initialized) in JavaScript, use the “typeof” operator. It outputs “undefined” if the operand/variable has not been defined. The typeof operator is very helpful in identifying whether the variable is defined because it does not generate a “ReferenceError” if the variable is not declared. This tutorial demonstrated the way to identify whether the variable exists (defined/initialized) or not.

Share Button

Source: linuxhint.com

Leave a Reply