undefined vs not defined in JavaScript

Full-stack developer. Checkout my Github & Spotify. https://bio.link/aditijalaj
Prerequisites
If you are just getting started with or already learning JavaScript then this article is totally for you. Let's get started.
Introduction
undefined and not defined are definitely not the same, in fact they are not even related. Did you know how does a variable even get the value of undefined ? If you don't keep reading.
How does a Variable get the value of undefined really?
So a Javascript program is executed in 2 phases - 1. Memory allocation and 2. code execution The Javascript engine reads a program from top to bottom and assigns memory to variables and functions.
Look at the code below-
var a = 3;
function b() {
console.log(a);
}
b();
Here, in the first phase of execution that is Memory allocation, the JS engine will allocate undefined to all the variables there in the program. While to functions it'll assign the function copy as it is. So, a=undefined and b = { console.log(a)}
Say you had used arrow function to declare function b like this-
const b=()=> {
console.log(a);
}
b();
Then in b would have been assigned undefined in the memory allocation phase instead of the function copy just how a variable is assigned.
Then in the second part, that is, the code execution phase the variable a would be assigned the value 3 and the function will be invoked.
Now inside the function, it'll look for the value of a which holds a value of 3, and log it.
Let's consider a slightly different scenario-
var a ;
const b=()=> {
console.log(a);
}
b();
You see we haven't assigned a value to variable a. On invoking the function , what do you think will be logged for the value of a . Yes, it'll be undefined because it was already assigned that value in the 1st phase
Now take a look at the following code-
var a = 3;
const b=()=> {
console.log(c);
}
b();
Here, it'll follow the same two steps of memory and code execution, but the variable c isn't allocated any value as it wasn't declared anywhere. So in the case, we'll get the below
ReferenceError -c is not defined.
Conclusion
So that was a basic understanding of how Javascript decides what's not defined and undefined. However, this was a small part of how the Javascript engine executes a code and there's a bigger part to this where I'll be explaining further how this happens with the Execution context and Call stack in my future blog.
So stay tuned for that, and feel free to provide your valuable feedback.
If you found this article helpful, do consider following for more blogs on JavaScript, React, front-end web design, and more.
To connect over web development, say hi to me on my twitter https://twitter.com/AditiJalaj OR LinkedIn https://www.linkedin.com/in/aditi-jalaj-5b921612a/


