undefined
is a very special keyword in JavaScript and is not present in other languages.- JavaScript code is executed in a different way. It creates a global execution context and allocates memory to all variables and functions even before a single line of code is executed.
undefined
comes into the picture exactly at this moment. Let us go through a small piece of code and then understandundefined
and not defined in detail.
INPUT -->
var a;
console.log(a);
console.log(x);
OUTPUT -->
undefined
Uncaught ReferenceError: x is not defined at <anonymous>:3:13
- When JavaScript is in the memory allocation phase it declares
a
and puts a placeholderundefined
to it. - When a variable such as
x
is not declared in the code and the program tries to access it, aReferenceError
is thrown at the user saying not defined. undefined
does not mean empty. It is a special keyword. It is a placeholder which takes up its own memory and is kept for the time being until the variable is assigned some value.- JavaScript is a loosely typed or weakly typed language, which means if a variable is declared and assigned a value of a certain data type, the datatype can later be changed.
var a = undefined;
- Never do this mistake. It can lead to a lot of inconsistencies and is not a good practice.
To further read about this topic in-depth, do check out these resources: