Categories
JavaScript Answers

How to Check if a JavaScript Variable Exists?

Spread the love

JavaScript variables may be declared without setting a value for them.

They can also be set to undefined .

In this article, we’ll look at how to check if a JavaScript variable is initialized or whether it’s undefined .

The typeof Operator

One way to check if a JavaScript variable exists is to use the typeof operator.

For instance, we can write:

let x;  
console.log(typeof x === 'undefined')

If x isn’t initialized, then it’s the same as setting it to undefined .

So typeof x returns 'undefined' .

Therefore, the console.log returns true .

Falsy Check

We can also check if a variable is falsy to see if it’s a falsy value, which includes undefined , null , '' (empty string), 0, NaN , or false .

Truthy value is any value other than those values.

For instance, we can write:

let x;  
console.log(Boolean(x))

Then console log logs false since x is uninitialized, so it’s undefined .

And since Boolean converts any falsy value to false , that’s what we get.

Equivalently, we can use !! to do the same thing:

let x;  
console.log(!!(x))

Conclusion

We can use the typeof operator or the Boolean function to check if a variable is initialized or not.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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