Front end code

Checking if a variable exists in JavaScript or TypeScript

That's probably one of the most popular questions that an engineer may ask when learning either JavaScript or TypeScript languages.

In some situations, when you don't know if the variable is defined, you may need to check if it exists. That can occur when you are working with objects that were passed into function. Another scenario, is that there is a need to parse JSON data and determine if some property exists there.

There may be more cases when this check is needed. However, the solution is pretty simple. The JavaScript language offers the typeof operator. It allows you to get a string that contains a type of the value.

Now, let's see an example. To check if the variable is defined, you may use the code like the following:

if (typeof sample !== 'undefined') {
    // You may obtain value from the variable "sample"
} else {
    // The "sample" variable is not defined
}

As you can see, that usage is very simple. Now you can write additional logic that will handle both cases, when the variable is either defined or not.

It's also possible to test if some property is defined inside of an object. To do that, you may write a code like the following:

if (typeof data.state !== 'undefined') {
    // You may obtain value from the property "state" of the object "data"
} else {
    // The "state" property is not defined
}

Precedence of the typeof operator

The precedence of the statement in your code is very important. The typeof operator has higher priority than some other operator types, like multiplication, division, addition, subscation and others.

As result, the following code:

typeof sample + " world";

Is not the same as the below:

typeof (sample + " world");

The results of such a calculation will be different. And you have to take this into account when making statements in your code.

The undefined property

The undefined property is another solution that you can use to check if the variable exists or not. It belongs to the global object scope. And the value of the property is an undefined as well.

Now, let's write a code that tests if the "sample" variable is defined or not. Please see it below:

if (sample !== undefined) {
    // You may obtain value from the variable "sample"
} else {
    // The "sample" variable is not defined
}

But please pay attention that the undefined property works a little differently. When you are using the typeof operator and the "undefined" string value, the error will not be thrown if the variable has not been declared in the code.

But if you do use it, and the variable does not exist, there will be an exception. Please see the example below:

// The below statement will throw a ReferenceError, since the "sample" is not available in the code.
if (sample === undefined) {
    // Other code here
}

However, the above check may work when testing if properties exist inside of an object. Please see our code below:

let sample = {};

if (sample.data === undefined) {
    console.log("not defined");
} else {
    console.log("defined");
}

The above code will not crash, since the object does exist. However, the property "data" is not defined, and the console output will be like the following:

not defined

Regular conditional check

The other very simple method to check that the variable exists is to use the conditional if statement. It should be done without any comparison operators. The value of the variable may be converted to either true of false. Following is the sample code:

let sample = {};

if (sample.data) {
    console.log("property is defined");
} else {
    console.log("property is not defined");
}

Please keep in mind, that the code like above will evaluate to true even if the "data" property is either null, empty string, NaN, 0 number, or simply a false value.

The other note is that such a solution will not work for regular variables. There may be a ReferenceError exception if the code is like the following:

// Will produce such error:
// ReferenceError: sample is not defined
if (sample) {
    console.log("variable is defined");
} else {
    console.log("variable is not defined");
}

Optional chaining operator

The JavaScript specification also contains support of the optional chaining operator. Which is ?.. It allows you to check if the property exists in the parent object by simply using the questions mark and the dot.

Please see our example below:

let sample = {};

if (sample?.data?.state) {
    console.log('"state" property is defined');
} else {
    console.log('"state" property is not defined');
}

You will see a message that the "state" property is not defined. That's because the sample object is null and contains no inner properties.

Checking if the variable exists in the global scope

There is an alternative solution to the methods that we listed above. The "in" operator allows to check if some variable exists in the global object.

Please review the code example that is shown below. There, we check that the "sample" variable is inside the window object.

if ("sample" in window) {
    // variable "sample" is defined globally
} else {
    // variable "sample" is not defined globally
}

But, this method may not be suitable in all cases. However, if you believe it can benefit, you may consider using it in your code.

Using "void 0" statement

There is a special case that allows to check for an undefined state. For that purpose, we can use the void operator. It evaluates some expression, and after that produces the undefined primitive.

It our situation, it's just enough to pass 0 number as an argument into the void operator. That will return the undefined state, which is compared to our variable. Please see the code example below.

var sample;

if (sample === void 0) {
    console.log(`variable "sample" is not undefined`)
} else {
    console.log(`variable "sample" is undefined`)
}

Please take note that the variable is declared there. Otherwise, if it's not available, you will see the "ReferenceError" error exception.

hasOwnProperty method

There is another interesting method that we have to list in this article. The JavaScript language provides the hasOwnProperty() method, which allows us to check if a property exists inside of some object. It returns either true or false state.

As result, if we call this method on a window object, it will tell us if the property is defined in a global scope. Please review our code sample:

var message = "hello";

console.log(window.hasOwnProperty("message")); // prints "true"

console.log(window.hasOwnProperty("notification"));  // prints "false"

After running such a code, you will see that the console contains "true" state for the "message" variable, since it is defined. But there will be "false" state for the "notification" property, since it is not defined.

Using try/catch block

There may be specific situations when it's not easy to add any of the methods listed above. Or you may be making code for some critical project and really need to ensure that the script will not crash.

In those cases, you can always use the standard try/catch block. It will help to catch an issue when the code tries to access some property that does not exist.

Please review our sample below:

try {
    data.message = 'Hello world!!!';
} catch (error) {
    console.log('Error has occurred', error);
}

The "message" property does not exist there. However, the code will not crash and proceed working even after the try/catch block. Also, an error message will be printed to the console.

Conclusion

As you have seen in this article, there are many interesting methods that allow you to check if the variable exists. Every method has its own advantages and disadvantages. But that is for you to decide how to build the code, as some solutions may fit only into specific functions and classes.

Related Articles

Html source code

How to change a CSS class in JavaScript

Source code with loop

Loop through an array in JavaScript

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *