Difference between undefined and not defined in JavaScript

Difference between undefined and not defined in JavaScript

Table of contents

In this article we will try to understand what is the difference between “undefined” and "not defined" in JavaScript.

In JavaScript we often come across with outputs like undefined and not defined. So what is the main difference between undefined and not defined?

undefined

Undefined is when we have declared a variable but we have not assigned any value to that variable. It is important to know that the memory has been allocated for that particular variable but it just does not have a value assigned to it yet.

So here in the above code , the Javascript first allocates memory to the variable a. So far only memory is allocated but it’s not been assigned a value.

So when we console.log a, we get undefined error. The var a exists in the program but it just doesn’t has a value yet.

But here in the above code var a is declared, memory is allocated for that var and it has also been given a value. So when we console.log we get the value of a as 100.

Another example where variable a is undefined.

not defined

In JavaScript not defined error occurs when we try to console.log or call a variable that is not declared anywhere the entire JavaScript program.

Note that undefined means that variable exists somewhere in the program but not defined means that var does not exist in the program

So here in the above code we are trying to console.log a variable (b) that is not declared. Hence it throws not defined error.

console.log(b); //not defined error
console.log(a); // undefined error
var a=100;
console.log(a)  // output is 100

Did you find this article valuable?

Support Venkatesh K by becoming a sponsor. Any amount is appreciated!