Undefined vs Undeclared in JavaScript

The difference between undefined and undeclared variables in JavaScript is:

  • Undefined variable means a variable has been declared but does not have a value.
  • Undeclared variable means that the variable does not exist in the program at all.

This is a comprehensive guide to understanding the differences between undefined and undeclared in JavaScript.

Examples

The best way to understand the difference between undefined and undeclared in JavaScript is by having a look at examples.

Example 1: Undefined Variable

To see an example of an undefined value, declare a variable but do not assign it a value:

var dog;
console.log(dog);

Output:

Undefined

This is what is meant by an undefined variable in JavaScript. It’s been declared but doesn’t hold value.

Undeclared Variable

An example of an undeclared variable is when there is no such variable in the program.

For example, let’s try to print a variable called cat without having such a variable in the program:

console.log(cat);

Output:

ReferenceError: cat is not defined

How to Check If a Variable Is Undefined in JavaScript

To check if a variable is undefined in JavaScript, use a direct check using the triple equals operator (===):

someVar === undefined

How to Check If a Variable Is Undeclared in JavaScript

If you try to access an undeclared variable in JavaScript, you get a ReferenceError. This is consistent because if there is no such variable, you cannot use it.

But does this mean you need to do error handling to check if a variable exists in a program?

Nope.

The typeof operator is a great help in this case.

To check if a variable exists in the program, use the typeof operator. It does not throw a ReferenceError with an undeclared variable. Instead, it returns ‘undefined’.

For instance, let’s check if a non-existent variable cat is found:

if(typeof cat === "undefined") {
    console.log("Cat does not exist in the program");
}

Output:

Cat does not exist in the program

Conclusion

Today you learned what is the difference between undefined and undeclared in JavaScript.

To recap:

  • Undefined means you have created a variable but it does not have a value.
  • Undeclared means you do not have that variable at all.
Scroll to Top