HomeLinuxJavaScript Test if Variable Exists (Outlined/Initialized)

JavaScript Test if Variable Exists (Outlined/Initialized)

Whereas coding, it’s generally essential to test a variable’s existence to set off a particular performance. Suppose a developer needs to offer default values for a variable. In that case, they will test if the variable has been outlined or initialized and set it to the specified default worth. Additionally, checking if a variable exists may also help the builders to establish bugs within the code.

This tutorial will reveal the way in which to establish whether or not the variable exists and is outlined/initialized or not.

Easy methods to Test/Confirm if a Variable Exists (Outlined/Initialized) in JavaScript?

To find out if a variable is outlined or initialized in JavaScript, use the “typeof” operator. The typeof operator that outputs a string signifies the kind of the given operand. If the operand is a variable that isn’t outlined/initialized, the typeof operator returns “undefined”.


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

typeof variable !== ‘undefined’


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

Now, confirm the variable “x”, and variable “y” are outlined/initialized or not. To take action, test the variable’s sort is just not equal to the “undefined” utilizing the “typeof” operator:

if(typeof x !== ‘undefined’){
 console.log(“Variable x is outlined”);
if(typeof y !== ‘undefined’){
 console.log(“Variable y is outlined”);

The output reveals that the variable “x” is outlined whereas the “y” is just not, as a result of because the typeof operator returns “undefined”:

It’s also possible to test with out “typeof” operator, however it can throw an distinctive error. In distinction, the typeof operator doesn’t throw/give a reference error if the variable is just not declared/initialized:

if(x !== ‘undefined’){
 console.log(“Variable x is outlined”);
if(y !== ‘undefined’){
 console.log(“Variable y is outlined”);

It produces an distinctive error on the variable “y” which isn’t declared/initialized:

We’ve offered all of the important directions related to confirm the variable declared/initialized in JavaScript.


To find out whether or not the variable exists (outlined/initialized) in JavaScript, use the “typeof” operator. It outputs “undefined” if the operand/variable has not been outlined. The typeof operator could be very useful in figuring out whether or not the variable is outlined as a result of it doesn’t generate a “ReferenceError” if the variable is just not declared. This tutorial demonstrated the way in which to establish whether or not the variable exists (outlined/initialized) or not.



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments