JavaScript execution order: why is this conditional code executed after the code that follows it?

if(true) { let m = "yo"; console.log(m); } console.log(m) 

Output:

 ReferenceError: m is not defined yo 

Thus, the code in line 4 is executed after the code in line 8.

Does my use of let use this?

EDIT: After reading the comments, I realized that this might be due to my runtime. Here's how I see it in Firefox at night:

firefox nightly let m

EDIT 2: If this is really just my runtime, are there any consequences for the production code due to something like that? Inconsistent browser behavior? How can I protect myself from this?

+6
source share
1 answer

So, I think the behavior of the FF environment is fine. A quick look at the specification (6.2.3.1, etc.) Indicates that the code should be executed line by line, up to the second console.log(m) , into which a ReferenceError .

I suspect that it only “looks funny” because of the order in which the console chooses to render the first console.log and exception messages (for example, this is the opposite of Chrome).

Whether the order to process the console is an error or not, I leave it to others.

The following confirmation of my analysis appears, showing a warning before the exception is logged.

 if(true) { let m = "yo"; alert(m); } console.log(m) 
+2
source

All Articles