DEV Community

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

Posted on • Originally published at codingdeft.com

3 1

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❀ or a friendly comment on this post if you found it helpful!

Okay