JavaScript

How to check if a variable exists or is defined in JavaScript

In some cases, your JavaScript code may need to depend on a particular variable. If you want to check if a variable has been initialized or defined (i.e. if a variable has been declared and received a value), you can use the typeof operator.

The typeof operator is useful for checking the data type of a variable. Here is a list of the values returned by the typeof operator:

  • “Number” – the variable is a number.
  • “String” – the variable is a string.
  • “Boolean” – the variable is a boolean.
  • “Object” – the variable is an object.
  • “Null“ – the variable is null.
  • “Undefined” – the variable is undefined.

So in this case, to check if a variable exists or is defined, use the typeof operator and check if the returned value is “undefined”.
 

 

How to check if a variable exists or is defined in JavaScript
var nbr = 10;

if (typeof nbr == 'number') {
    document.write(nbr + " is a number <br/>");
}

if (typeof nbr == 'undefined') {
    document.write("The variable nbr does not exist <br/>");
} else {
    document.write("The variable nbr exists<br/>");
}

if (typeof str == 'undefined') {
    document.write("The variable str does not exist <br/>");
} else {
    document.write("The variable str exists<br/>");
}

Output:

10 is a number
The variable nbr exists
The variable str does not exist
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 *