Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About var/const, why this code will work?

Open dev console (or in node.js), enter the following code by sequence:

a = 1
var a = 2
const a = 3

screenshot1

As you can see it works, but if you enter all the code at once, you will get an error, which I think is more reasonable screenshot2

I guess the only difference is hoisting, if you input all the code at once, it will be treated as:

var a
a = 1
a = 2
const a = 3

But I don't understand why it works when you enter line by line, also if you skip the first line, you get an error as expected

enter image description here

like image 709
CodinCat Avatar asked Dec 29 '16 06:12

CodinCat


1 Answers

In global scope of the environment a variable can be assigned and declared irrespective of the type, therefore when you enter following code in sequence, it works.

z = 1
var z = 2
const z = 3

value of z is 3 now

Now lets say we execute all this at once

    z = 4;  var z = 5;  const z = 6;

value of z is still 3

the interpreter in this case will throw error because here it will try to execute all the above statement once as a block and now it has found multiple declaration for 'z' and thus will throw an error for the whole block and will not execute even the first part i.e z = 4;

the statement where everything is executed at once is equivalent to

(function foo(){ z = 4; var z = 5; const z = 6;  })();
like image 157
Achal Saini Avatar answered Oct 23 '22 05:10

Achal Saini