DEV Community

Cover image for How to check if a variable is defined in JavaScript
collegewap
collegewap

Posted on • Originally published at codingdeft.com

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:

if (typeof x !== "undefined") {
  console.log(x)
}
Enter fullscreen mode Exit fullscreen mode

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.

let x
if (typeof x !== "undefined") {
  console.log(x)
}
Enter fullscreen mode Exit fullscreen mode

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

let x = 1
if (typeof x !== "undefined") {
  console.log(x)
}
Enter fullscreen mode Exit fullscreen mode

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

const person = {
  name: "John",
}

if (person.hasOwnProperty("age")) {
  console.log(person.age)
}
Enter fullscreen mode Exit fullscreen mode

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.

window.y = 10

if (window.hasOwnProperty("y")) {
  console.log(window.y)
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)