Check if variable is defined or not

How can I check whether a variable is defined in JavaScript?

In this tutorial, we will learn to check the existence of the variable, which means whether the variable is declared and initialized or not in JavaScript. In many scenarios, JavaScript programmers need to check the presence of the variable. Otherwise, it throws a reference error if we use it without declaring or defining it.

For example, Programmers have defined the variable and it is uninitialized. Programmers want to change the variables’ value through the data they will get from API calls. Suppose that the value of the uninitialized variable is not updated due to some error during the API call. If the programmer tries to access the uninitialized variable without checking its value, it will throw an error.

Before we move ahead, let’s clarify the difference between the defined and undefined, and null variables.

Const data = 10; //variable is declared and defined (initialized with value 10) Const data; //variable is declared but its value is undefined. Const data = null; // declared and defined (initialized with "null" value). data = 10; // undeclared but defined (initialized with 10). data // undeclared and undefined, type of the variable is undefined

So, now users can clearly understand that if the variable is not initialized, its default value is “undefined.” If we initialize the variable with a “null” value, we can call it a null variable. If users use the undefined or null variables in the code, they have to face the error.

Читайте также:  Call sql function php

We have different ways to check whether the variable is “undefined”.

  • Using the typeof Operator
  • Using the if statement
  • Use the window.hasOwnProperty() method
  • Use the try/catch block

Using the typeof Operator

The typeof operator is helpful to get the data type of any variable. For undefined variables, the typeof operator returns the string “undefined”. We can use the string equality (“===”) operator, and we can compare the returned value from the typeof operator with the “undefined” string and check the existence of the variable.

Syntax

Users can follow the below syntax to use the typeof operator.

Parameters

  • variable_name − It could be any variable for which we want to check whether it is undefined or not.

In general, if we use an undefined variable as an operand of typeof variable, i.e. ‘typeof undefined_variable,’ it doesn’t throw an error, but if we use it at any other place in our code, it throws an error.

Example 1

The below example demonstrates how to check if variable is defined or undefined using the typeof operator. The variable age is declared but assigned with a value so it is defined.

     

The typeof operator: Check if variable is defined or not

let age = 20; let contentDiv = document.getElementById("contentDiv"); if (typeof age === "undefined") < contentDiv.innerHTML = " variable age is undefined. "; > else < contentDiv.innerHTML = "Variable age is defined. "; >

Here the variable age is declared with value 20.

In the above output, users can see that we have declared the «age» variable, and its value is initialized with 20, so it prints the output as defined.

Try the above program with the following-

var age; // undefined age = 20; // defined var age = 20; // defined var age = null; // defined age; // Uncaught ReferenceError: age is not defined (in Console)

Please refer to this article to find the difference between undefined and not defined.

Using the if statement

We can check if a variable is ‘defined’ or ‘undefined’ using the if statement. You need to check using the following syntax.

Syntax

if (variable_name === undefined)< //block of code to be executed. >

Parameters

  • variable_name − It should be the name of the variable for which we want to check if it is defined or not.

Here the variable_name===undefined is the condition of the if statement. If the variable_name is undefined the result of the condition is “true”, else the result of the condition is “false”. Look at the below example.

Example 2

  

The if statement: Check if variable is defined or not

In the above output, users can see that we have declared the «rank» variable, but its value is uninitialized, so it prints the output as undefined.

Use the window.hasOwnProperty() method

We can access every globally defined variable, object, or function using the window property in JavaScript. The “window” works as a global object to check any variable’s existence. We can call the hasOwnProperty() method for the window object to confirm that it contains the variable. It returns a boolean value according to whether a variable is defined or not.

Syntax

let isUndefined = window.hasOwnProerty('variable_name').

Parameters

  • variable_name − It should be the name of the variable for which we want to check if it is defined or not.

Return − It returns “true” if the variable_name exists (either defined or declared), else it returns “false

Example 3

The below example demonstrates how we can check variable is undefined using the window.hasOwnProperty() method.

     

The window.hasOwnProperty() method

Checking the existence of a variable

// isdefined variable either get true or false value var isdefined = window.hasOwnProperty('data'); let variableDiv = document.getElementById("variableDiv"); // function to check if variable is undefined or not. function checkExistanceOfVar() < if (isdefined) < variableDiv.innerHTML = " Variable data exist "; > else < variableDiv.innerHTML = " Variable data doesn't exist "; > > // call the function checkExistanceOfVar();

In the above output, users can see that ‘data’ variable doesn’t exit, so the window.hasOwnProerty() method returns false and control goes to the else block.

However, above method will not work with the let and const variables. Users can use above method to check existence of functions and variable declared with the var keyword.

Use the try/catch block

Generally, we use the try/catch block to save our code from crashing with an unknown error. The JavaScript returns the reference error when the variable is undefined or uninitialized. We can try to access the variable in the try block, and if any error occurs or the variable is undefined, control goes to the catch block, and we can resolve the error there.

Syntax

Users can follow the below syntax for the try/catch block.

Example 4

In the below example, we have demonstrated how to use try/catch block to check whether variable is undefined or not.

     

Checking if the variable id defined using the try / catch block.

let errorDiv = document.getElementById("errorDiv"); function checkExistanceOfVar() < // using the try/catch block try < let data = result; errorDiv.innerHTML = " result variable exist"; > catch (error) < errorDiv.innerHTML = error; >> // call the function checkExistanceOfVar();

In the above example, we are trying to assign undefined result variable to the data variable, so control goes to the catch block and it prints the ReferenceError.

Conclusion

We have seen three different approaches to checking whether a variable is undefined. The first approach is applicable in all conditions. Users can use the second approach only with the variable declared with the ‘var’ keyword. While using the third approach, users need to specify the error type in the catch block. Otherwise, control goes to the catch block due to other errors.

Источник

3 Ways to Check if a Variable is Defined in JavaScript

Post cover

From time to time you have to check whether a variable is defined in JavaScript. For example, to determine if an external script has been successfully loaded into the web page, or to determine if the browser supports a Web API ( IntersectionObserver , Intl ).

How to check if a variable is defined in JavaScript? The answer is not straightforward, so let’s find out!

Before I go on, let me recommend something to you.

The path to becoming good at JavaScript isn’t easy. but fortunately with a good teacher you can shortcut.

Take «Modern JavaScript From The Beginning 2.0» course by Brad Traversy to become proficient in JavaScript in just a few weeks. Use the coupon code DMITRI and get your 20% discount!

1. The states of a variable

Before jumping into specific techniques, I’d like to have an agreement on the related terms.

In the following 2 sections, let’s make clear what it means for a variable to be «defined»/»not defined» and «initialized»/»uninitialized».

1.1 Defined / not defined variable

A variable is defined when it has been declared in the current scope using a declaration statement.

The usual way to declarate variables is const , let and var statements, plus the function and class declaration statements.

Examples of defined variables:

Contrary, a variable is not defined when it hasn’t been declared in the current scope using a declaration statement.

Examples of not defined variables:

The scope sets the limits where the variable is defined and accessible. A scope in JavaScript is defined by a code block (for const and let variables) and by a function body (for const , let , var ).

Accessing a variable that’s not defined throws a ReferenceError :

1.2 Initialized / uninitialized variable

A variable is initialized when the declared variable has been assigned with an initial value.

Examples of initialized variables:

On the other side, a variable is uninitialized when the declared variable has not been assigned with an initial value.

Examples of uninitialized variables:

The value of an uninitialized variable is always undefined :

Knowing the possible states of variables, let’s consider the techniques to find whether a variable is defined or not.

The typeof operator determines the variable’s type. typeof myVar can evaluate to one of the values: ‘boolean’ , ‘number’ , ‘string’ , ‘symbol’ , ‘object’ , ‘function’ and ‘undefined’ .

The expression typeof missingVar doesn’t throw a ReferenceError if the missingVar is not defined, contrary to simple access of the not defined variable:

That’s great because you can use the expression typeof myVar === ‘undefined’ to determine if the variable is not defined:

Be aware that typeof myVar === ‘undefined’ evaluates to true when myVar is not defined, but also when defined and uninitialized. All because accessing a defined but uninitialized variable evaluates to undefined .

Usually, that’s not a problem. When you check if the variable is defined, you want it initialized with a payload too.

Of course, if the variable is defined and has a value, typeof myVar === ‘undefined’ evaluates to false :

When accessing a not defined variable, JavaScript throws a reference error:

So. what about wrapping the checked variable in a try block, and try to catch the reference error? If the error is caught, that would mean that the variable is not defined:

missingVar in the above example is not defined. When trying to access the variable in a try block, a ReferenceError error is thrown and catch block catches this reference error. That’s another way to check the variable’s existence.

Of course, if the variable is defined, no reference error is thrown:

Compared to typeof approach, the try/catch is more precise because it determines solely if the variable is not defined, despite being initialized or uninitialized.

4. Using window.hasOwnProperty()

Finally, to check for the existence of global variables, you can go with a simpler approach.

Each global variable is stored as a property on the global object ( window in a browser environment, global in NodeJS). You can use this idea to determine if the global variable myGlobalVar is defined: simply check the global object for corresponding property existence: window.hasOwnProperty(‘myGlobalVar’) .

For example, here’s how to check if the browser defines an IntersectionObserver variable:

var variables and function declarations, when used in the outermost scope (aka global scope), do create properties on the global object:

However, be aware that const and let variables, as well as class declarations, do not create properties on the global object:

In JavaScript, a variable can be either defined or not defined, as well as initialized or uninitialized.

typeof myVar === ‘undefined’ evaluates to true if myVar is not defined, but also defined and uninitialized. That’s a quick way to determine if a variable is defined.

Another approach is to wrap the variable in a try < myVar >block, then catch the possible reference error in a catch(e) < >block. If you’ve caught a ReferenceError , then the variable is not defined.

Finally, to check the existence of a global variable myGlobalVar invoke window.hasOwnProperty(‘myGlobalVar’) . This approach is useful to check if the browser supports a Web API.

What is your preferred way to check if a variable is defined?

Like the post? Please share!

Dmitri Pavlutin

About Dmitri Pavlutin

Software developer and sometimes writer. My daily routine consists of (but not limited to) drinking coffee, coding, writing, overcoming boredom 😉. Living in the sunny Barcelona. 🇪🇸

Dmitri Pavlutin

About Dmitri Pavlutin

Software developer and sometimes writer. My daily routine consists of (but not limited to) drinking coffee, coding, writing, overcoming boredom 😉. Living in the sunny Barcelona. 🇪🇸

Источник

Оцените статью