What is undefined vs not defined in JavaScript?

In JavaScript programming, we see errors like undefined, not defined, etc. They can be quite frustrating sometimes, butthey are easy to understand and can be solved.

Undefined

An undefined error is when we declare a variable in the code but do not assign a value to it before printing the variable.

let x; //we have declared X
function runX(){
return x;
}
//Since we did not assign x, it prints undefined
console.log(runX());

Not defined

A not defined error is when we did not declare the variable and tried to call that variable.

//x is not declared/defined
function runX(){
return x;
}
//So we have an error of X is not defined
console.log(runX())

In JavaScript, we can declare variables without adding const, let, or var, and we won’t get an error of undefined or not defined. This can be seen in the code below.

Code

x=6;
function runX(){
return x;
}
console.log(runX())

Let’s try another variation where we assign a value to the variable in the function block and then see if we get an error.

x;
function runX(){
x=5;
return x;
}
console.log(runX())

In the above example, we can see that xx is not defined. This is because we did not define it as a data type of let,const, or var. So, xx does not have space in its memory, and we can’t assign it a value.

Let’s see how this can be solved.

let x;
function runX(){
x=5;
return x;
}
console.log(runX());

We declared xx with let. Hence, we give it a space in memory to be able to assign values.

Our runX() returns a value of xx, even if we assign xx in the runX() block.

Free Resources