JavaScript
Programming
Web Development
Debugging
Error Handling

How to check a not-defined variable in JavaScript

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In JavaScript, a not-defined variable is one that has not been declared within the respective scope. Accessing such variables can lead to runtime errors. Therefore, it's crucial for developers to understand how to check for these variables to avoid unexpected crashes or bugs in their applications.

Understanding Scope and Declarations

Before diving into how to check for not-defined variables, let's revisit the basics of variable scope and declaration. JavaScript has three main types of scopes:

  1. Global Scope
  2. Function Scope
  3. Block Scope

Variables can be declared using var, let, or const, each affecting scope and reassignment differently. var declares a variable globally, or locally to an entire function regardless of block scope. let and const are newer and declare variables that are block-scoped.

The Problem with Not-Defined Variables

A not-defined variable refers to any variable used in a program that has not been declared beforehand in the applicable scope. Accessing such variables results in a ReferenceError.

javascript
console.log(x); // ReferenceError: x is not defined

Strategies to Check for Not-Defined Variables

Using typeof

One safe way to check if a variable is defined is to use the typeof operator. typeof will return 'undefined' if a variable has not been declared, rather than throwing a ReferenceError.

javascript
if(typeof x === 'undefined') {
   // Code to define x or handle it being undefined
}

Try-Catch Block

For broader error handling, especially when executing chunks of code that might result in various types of errors, a try-catch statement can be used.

javascript
1try {
2   console.log(x);
3} catch (error) {
4    console.log('Error:', error.message); // Error: x is not defined
5}

Checking window or globalThis in Browser Environments

In web browsers, you might check the window object (a global object in client-side JavaScript) to see if a variable exists as a property of window.

javascript
1if('x' in window) {
2    console.log('x exists!');
3} else {
4    console.log('x does not exist!');
5}

Leveraging globalThis

For a more uniform approach that works in both browser and Node.js environments, you could use globalThis which provides a standard way to access the global scope.

javascript
if('x' in globalThis) {
    console.log('x exists!');
}

Summary Table of Methods

MethodUsage ContextProsCons
typeofAny contextSafe, no risk of ReferenceErrorOnly checks for 'undefined', not if actually declared
Try-Catch BlockAny contextCan handle any type of errorOverhead of error handling; verbose for simple checks
window or globalBrowserDirect check against global objectWeb-specific; not suitable for Node.js
globalThisBrowser and Node.jsUniform, works on multiple environmentsRequires modern JS environments

Additional Points to Consider

  • ESLint: Using a linter like ESLint can help catch uses of not-defined variables during development, reducing runtime errors.
  • Strict Mode: Enabling JavaScript's strict mode ('use strict';) helps in catching not-defined variables, as it prevents the use of variables that have not been declared.

Conclusion

Checking for not-defined variables is crucial for robust JavaScript programming. The choice of method can depend on the specific requirements of the project and the environment in which the code runs. Awareness and careful management of scopes, declarations, and associated best practices significantly enhance code quality and maintainability.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.