DEV Community

Love Gupta
Love Gupta

Posted on

How the JavaScript code works behind the scene ?

I have seen a lot of people who know frontend but don't know very well how JavaScript works. In this post, I will share my learning so that if anyone asks you about this topic, or if an interviewer asks you a question related to this topic, you will not be confused. Let's start! :

When we run our JavaScript code , at that time JavaScript engine execute that code in two phases that is
1-creation phase
2-execution phase

  • In creation phase , memory is allocated to all the variables and functions , for variables a special value Undefined is assigned to all variables and for function entire code gets copied in memory,

  • in execution phase js code is executed line by line and in this phase undefined value of variable is replaced by actual value that we were assigning in that variables

for ex:- let a=20 
Enter fullscreen mode Exit fullscreen mode

so firstly in creation phase memory is allocated to variable a with undefined value
after that in execution phase value 20 is assigned to a.

wait a minute guys

So here very interesting topic comes in picture that is hoisting .
In Hositing you can use a variable or function before it is declared, and JavaScript will still be able to find it.

However, variables created using the 'let' and 'const' keywords are also present in the TDZ (temporal dead zone), so we cannot access those variables before defining or declaring them. Attempting to do so will result in an error.

 console.log(a);
let a=20;
output :you can not access it before declaring 
Enter fullscreen mode Exit fullscreen mode

However, if we use the 'var' keyword with variables, the variables that are created using the 'var' keyword do not exist in the TDZ. Therefore, accessing them before declaring or defining them will not result in an error, but will instead show 'undefined'.

console.log(a);
var a=20;
ouput: undefined
Enter fullscreen mode Exit fullscreen mode

But It's generally a good practice to declare all variables and functions at the top of their respective scopes
I hope you will get useful information and I welcome your suggestion 😀

Top comments (0)