Undefined And Undeclared Variables: Undeclared variables are those that are not declared in the program (do not exist at all), trying to read their values gives runtime error. But if undeclared variables are assigned then implicit declaration is done. Undefined variables are those that are not assigned any value but are declared in the program. Trying to read such variables gives special value called undefined value.

Example of Undefined Variable:

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

var monkey;
console.log(monkey);

Output:

Undefined

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

Example of 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(cow);

Output:

ReferenceError: cow is not defined

Difference Between Undefined And Undeclared Variables

Here is the difference between undeclared and undefined variables.

UndeclaredUndefined
These are the variables that are absent from the heap of memory.These variables are the ones that are physically present in memory, but the programmer hasn’t explicitly assigned anything to them.
The lack of var, let, or const in the programming language is regarded as an undeclared variable.The fact that JavaScript assigned it to the variables causes them to be regarded as being undefined.
JavaScript will throw a Reference error if we attempt to access them during code execution.We will receive the value “undefined” if we attempt to access these variables.

How To Check If A Variable Is Undefined or Undeclared?

To check if a variable is undefined in JavaScript, use a direct check using the triple equals operator (===). === is strict equality operator ,it returns true only when the two operands are having the same value without any type conversion.

someVar === undefined

In order to check 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?

Let’s check if a non-existent variable cow is found:.

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

Output:

Cow does not exist in the program

Also Read:

Categorized in: