undefined vs not defined in JS

undefined vs not defined in JS

ยท

2 min read

Let's understand the difference between undefined and not defined in JavaScript.

undefined

Whenever a JS code is executed, a Global Execution Context is created. During the first phase(memory allocation phase), all the variables are assigned a value of undefined.

undefined value is assigned to a variable when we want to assign memory to it.

not defined

When we try to access a variable which has not yet been defined or no memory has been allocated to it, then we get a value of not defined.

Let's have a look at this code snippet:

carbon (6).png

On executing this code snippet in console, we get:

hashnodePic.png

EXPLANATION

  1. Line 1 logs undefined, because initially the variable gets assigned a value of undefined in the memory area(variable environment) of the Global execution context.

  2. Line 2 logs 10 , because before doing a console.log, we are overwriting the initial value of a from undefined to 10 .

  3. Line 3 logs not defined, because we haven't attached anything to the variable b , so JS engine assumes that it is in the window object and tries to search it there . But, it can't find b in the window object and hence it logs not defined.

If you like this and want to learn more about such JS concepts, Akshay Saini's Namaste ๐Ÿ™ JavaScript would be a great start.