DEV Community

Discussion on: How JavaScript engine execute this code?

Collapse
 
uddeshjain profile image
Uddesh

Hey Shubham, Hoisting doesn't work like this. We can't just declare the variable and assign where we want in our code there are some rules for this.

1) Only declaration will hoist not the assignment.

2) No executable logics like functions will hoist.

So if you write

a = 10;
console.log(a);  // 10
var a;

The output will be '10'

Why?

because javascript engine hoist declaration of the variable a and put it on the top then it will hit the declaration part a = 10; then console.log(a) will be executed. so eventually the javascript engine will take it like this.

var a;
a = 10;
console.log(a)  // 10

In your code, you are trying to access a and name before the declaration and that's totally fine but you have to assign the variable before you call them.

I hope it makes sense. Let me know if you have more queries.

Collapse
 
coderoo7 profile image
Shubham

Well thanks for your reply. I understand hoisting concept but what I'm not able to understand what happen when JavaScript engine compile the code.

console.log(a); log 'undefined'
var a=10;

According to you var a hoist to top but what I actually understand is that when JS engine compile the code it set the var 'a' to top and set it to undefined and at time of execution assignment operation is done.
That's why log is undefined for var 'a' but when JS engine read a=10 then it assign the value 10 to var a.

Collapse
 
uddeshjain profile image
Uddesh • Edited

Yes exactly, each and every variable assigned undefined unless you assign some value to it that's why console.log(a) says undefined.

Collapse
 
dizefurkan profile image
Said Furkan Dize

Hey,

Check out the "use strict".
It's throw an error when you try to declare an variable without "var", "const" or "let"

Collapse
 
uddeshjain profile image
Uddesh

That's a different case.

Thread Thread
 
dizefurkan profile image
Said Furkan Dize

No man. You gived an example on your vomment. That's why i wrote that comment.
When you use strict you cant declare an variable like: "a: 10"