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.
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 Xfunction runX(){return x;}//Since we did not assign x, it prints undefinedconsole.log(runX());
A not defined error is when we did not declare the variable and tried to call that variable.
//x is not declared/definedfunction runX(){return x;}//So we have an error of X is not definedconsole.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.
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 is not defined. This is because we did not define it as a data type of let
,const
, or var
. So, 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 with let
. Hence, we give it a space in memory to be able to assign values.
Our runX()
returns a value of , even if we assign in the runX()
block.