Come with a Question. Leave with a Solution.

How to Check if a Variable or Constant is Defined in JavaScript

...

JavaScript

November 27, 2023

Ensuring Variables and Constants are Defined in JavaScript: Best Practices

When working with JavaScript, developers often need to verify whether a variable has been declared or a constant has been defined before using it in their code. This can help avoid errors like ReferenceError or TypeError and ensure that your scripts run smoothly. In this article, we will explore how to check if a variable is set or if a constant is defined in JavaScript.

Checking if a Variable is Set

In JavaScript, variables can be declared using var, let, or const. Each has a slightly different scope and behavior, but the methods for checking whether they are set or declared follow similar patterns.

1.  Using typeof

The typeof operator can be used to check if a variable is defined (i.e., declared). If the variable has not been declared, typeof will return "undefined" without throwing an error.


let myVariable;

if (typeof myVariable !== 'undefined') {
  console.log("Variable is set");
} else {
  console.log("Variable is not set");
}

Even if myVariable is not declared at all, using typeof myVariable will return "undefined" and not cause an error. This makes typeof a safe way to check for variable declaration.


if (typeof someVariable === 'undefined') {
  console.log("Variable is not defined");
}

Note: typeof works well for checking variables declared with var, let, or const, as well as global variables.

2.  Using if Statements

Another way to check if a variable has been set is to use an if condition. If a variable has been declared but not assigned a value, it will have the value undefined, which evaluates to false in an if statement.


let myVariable;

if (myVariable) {
  console.log("Variable is set");
} else {
  console.log("Variable is either undefined or falsy");
}

However, this approach can be misleading because it will also evaluate false for variables that have falsy values, such as 0, null, NaN, or an empty string "". It’s important to distinguish between a variable being truly undefined and having a falsy value.

3.  Checking for null

Sometimes, you may want to explicitly check whether a variable is null (which indicates an intentional absence of a value) versus being undefined (which indicates the variable was declared but not initialized). This can be done using a strict comparison (===):


let myVariable = null;

if (myVariable === null) {
  console.log("Variable is null");
} else if (myVariable === undefined) {
  console.log("Variable is undefined");
} else {
  console.log("Variable is set");
}


Checking if a Constant is Defined

In JavaScript, constants are declared using the const keyword. Unlike variables, constants must be initialized at the time of declaration and cannot be reassigned. However, you can still check if a constant is defined or declared.

1.  Using typeof with Constants

Just like with variables, you can use typeof to safely check whether a constant has been declared. If it hasn’t been declared, typeof will return "undefined".


if (typeof MY_CONSTANT !== 'undefined') {
  console.log("Constant is defined");
} else {
  console.log("Constant is not defined");
}

This approach is useful because attempting to access an undeclared constant directly will result in a ReferenceError, while using typeof avoids that issue.

2.  Handling Block-Scoped Variables (let and const)

Both let and const are block-scoped, meaning that they are only available within the block in which they are defined. Trying to check for a let or const variable outside its block will result in a ReferenceError. However, you can use typeof to safely check for their presence without causing an error.


{
  const MY_CONSTANT = 42;
  console.log(typeof MY_CONSTANT); // 'number'
}

console.log(typeof MY_CONSTANT); // 'undefined' (outside of the block)


Important Considerations

1.  var vs. let and const

  • Variables declared with var are function-scoped or globally scoped, and using typeof on undeclared var variables returns "undefined".
  • Variables declared with let or const are block-scoped. Accessing them before declaration results in a ReferenceError (they are in the "temporal dead zone" from the start of the block to where they are declared).

2.  Global Variables

In JavaScript, variables declared in the global scope are properties of the global object (window in browsers). You can check for a global variable using window.hasOwnProperty() or simply checking the existence on the window object:


if (window.hasOwnProperty('globalVar')) {
  console.log("Global variable is defined");
}

if (window.globalVar !== undefined) {
  console.log("Global variable is set");
}


Conclusion

In JavaScript, checking if a variable is set or a constant is defined can be done using different techniques depending on your needs. The typeof operator is the safest and most widely used approach, as it doesn’t throw errors even for undeclared variables or constants. Additionally, understanding how scope and block-scoping affect variable access is key to writing robust code.

Use these methods to avoid unexpected errors in your scripts and ensure that your variables and constants are properly checked before they are used in your code!


Also read: 3 Ways to Check if a Function is Defined in JavaScript

Also read: Why typeof Returns 'Object' for JavaScript Arrays

Also read: Var, Let, and Const in JavaScript - Key Differences Explained

Is this article helpful?

error handling

user
Admin
About Author

A full stack web developer specializing in frontend and backend web technologies. With a wealth of experience in building dynamic and robust web applications, he brings expertise and insights to his articles, providing valuable guidance and best practices for fellow developers. Stay tuned for more useful content.