Skip to content

How to check if a variable is defined in JavaScript

Sep 2, 2022Abhishek EH2 Min Read
How to check if a variable is defined in JavaScript

Are you annoyed by the following error and want to put check to see if a variable exists before accessing them?

ReferenceError: x is not defined

In this tutorial, we will discuss the same.

Checking if a variable is defined

You can use the following condition to check if x is defined:

1if (typeof x !== "undefined") {
2 console.log(x)

The typeof operator returns the type of the variable and if it is not defined, or has not been initialized, returns "undefined".

It can also be checked if the variable is initialized or not. In the below code, the control will not go inside the if block.

1let x
2if (typeof x !== "undefined") {
3 console.log(x)

You will see the value of x logged into the console, if you execute the following code:

1let x = 1
2if (typeof x !== "undefined") {
3 console.log(x)

Checking if an object property is defined

If you need to check if a property exists within an object then you can use the prototype method hasOwnProperty

1const person = {
2 name: "John",
5if (person.hasOwnProperty("age")) {
6 console.log(person.age)

The above code will not log anything to the console.

The same can be used in the case of the window object. The below code will log 10 to the console.

1window.y = 10
3if (window.hasOwnProperty("y")) {
4 console.log(window.y)

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2024 CodingDeft.Com