Undefined vs Is not defined : The Javascript way

Undefined vs Is not defined : The Javascript way

Do you treat "undefined" and "not defined" same in Javascript as a beginner? Let me address the subtle difference between these terms.

ยท

2 min read

To even begin with the topic, let's first understand how javascript allocates memory and executes the code.

Everything in javascript happens inside the Global Execution Context. Execution context can be assumed as a box inside which there are two components - memory(aka variable environment) and code execution(aka thread of execution).

Inside memory, all the variables and functions are stored as key: value pairs,

eg a=10;

functions are stored as it is func store(){

...} (hint - functions are treated as heart of javascript)

Inside code execution, all the code is executed one by one(one after another). Since Javascript is an synchronous(code exec one after another) single-threaded language(one line of code at a time).

Assuming you are now able to connect the dots of allocation of memory and execution?

Let's begin,

Undefined.

Let's assume, you have typed var a = 10; even before the execution of this code, javascript will allocate memory in the memory environment which lies inside GEC.

Now we have a reserved memory for var a, which will be stored as a: undefined

Because when storing a variable it will allocate a placeholder for the variable.

After executing line var a = 10; if you console then an output will be 10.

Remember: Undefined != empty

It is a keyword which is kept undefined for the time being until any value is assigned to it.

If we declare only var a, and never assigned any value to it throughout the program it will remain as undefined.

Is not defined.

Ok now let's understand this term, this occurs simply when memory is not allocated to a variable and you try to console that.

Simply when the memory allocation does not happen it throws an exception that it is not defined.

Happy Coding โœŒ๐Ÿป

#JSbeginner

ย