Check If a Variable Exists or Defined in JavaScript

Javascript check if variable exists or defined example; In this tutorial you will learn how to check whether a variable has been initialized or defined in JavaScript using typeof operator.

In javascript the typeof operator is that it does not throw the ReferenceError if the variable has not been declared. E.g., if (typeof a !== ‘undefined’), then the variable is defined.

Example 1:

let a;

console.log(typeof a); // 'undefined'

// the variable `b` is not declared in our code
// but typeof doesn't throw an error
console.log(typeof b); // 'undefined'

if (typeof a !== 'undefined') {
  // the variable declared

if (typeof b === 'undefined') {
  // the variable no been declared

Note: The typeof operator did not throw an error even when we checked for the type of a variable named b, which is not declared in our code.