Undefined v/s Not Defined : JavaScript

Undefined v/s Not Defined : JavaScript

  • 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 understand undefined 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 placeholder undefined to it.
  • When a variable such as x is not declared in the code and the program tries to access it, a ReferenceError 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:

  1. undefined - MDN Web Docs
  2. Difference between undefined vs not defined - GeeksForGeeks