1

I know Temporal dead zone in es6. But I was confused about the procedure of the following code.

Javascript is a kind of Interpretive language.How does it knows there is a s will be declared in this block behind rather than use the s outside this block.

In an other word , what is the procedure of the following code ?? I am new here, please help me.

'use strict'
var s = 1;
if (true){
    console.log(s);
    console.log("AAA");
    let s = 2;
}
t3dodson
  • 3,949
  • 2
  • 29
  • 40
Wei.huan
  • 23
  • 2
  • What does "how does it know" mean? Do you mean how implementations do it under the hood? – Oriol Dec 21 '15 at 01:41
  • I mean how the program knows there will be a s=2 declare when run the code --console.log(s). Rather than use the s=1 ? Because it compiles before run??? – Wei.huan Dec 21 '15 at 03:25

1 Answers1

3

Javascript code is run in multiple passes. A first pass will go through and deal with all the declarations and assign them to their scopes.

That's how it "knows" that a left hand side reference to "s" will be declared via let for the scope of that if{} block, even though the non-hoisted let hasn't actually declared it yet.

Jimbo Jonny
  • 3,549
  • 1
  • 19
  • 23
  • Thank U .Does it means interpretive language also be complied first before it runs?? – Wei.huan Dec 21 '15 at 03:21
  • 1
    @Wei.huan - Part of the specs actually require these multiple passes. The language cannot operate properly without it. For example it would pretty hard to have function declarations or variable hoisting happen as spec'd without multiple passes. Honestly in my opinion the traditional divides between interpreted and compiled languages are being made fuzzy at this point. It is definitely NOT purely "interpreted" as in the definition of *"goes line by line without ever knowing what the next line is"*, because it definitely does not purely operate that way with its scopes and such. – Jimbo Jonny Dec 21 '15 at 03:40
  • Also keep in mind that there are quite a few different engines running JS at this point and, from what I've read, some of them even claim to compile right to machine code internally. – Jimbo Jonny Dec 21 '15 at 03:42
  • Thank u for your patient answer..I guess I get it. It still takes me some time and experience to understand the principle – Wei.huan Dec 21 '15 at 04:13