Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript execution order: why does this conditional execute after the code that follows it?

if(true) {
    let m = "yo";

    console.log(m);
}

console.log(m)

Output:

ReferenceError: m is not defined
yo

So the code on line 4 is being executed after the code on line 8.

Does my usage of let have anything to do with this?

EDIT: After reading comments I realised that this might be because of my runtime. Here's how I see it in Firefox nightly:

firefox nightly let m

EDIT 2: If this is indeed just my runtime, then are there implications for production code because of something like this? Inconsistent behaviour across browsers? How do I guard against that?

like image 524
Aditya M P Avatar asked Nov 20 '15 11:11

Aditya M P


People also ask

What is the order of execution in JavaScript?

JavaScript is synchronous. This means that it will execute your code block by order after hoisting. Before the code executes, var and function declarations are “hoisted” to the top of their scope.

Does JavaScript run sequentially?

39.1. 2 JavaScript executes tasks sequentially in a single process. This loop is also called the event loop because events, such as clicking a mouse, add tasks to the queue.


1 Answers

So I think the behaviour of the FF runtime is OK. A cursory glance the spec (6.2.3.1 etc) indicates that the code should run line by line, until the second console.log(m) at which point a ReferenceError is thrown.

I suspect it only "looks funny" because of the order in which the console is choosing to render the first console.log and the exception message (it is the inverse of Chrome for instance).

Whether the rendering order to the console is considered a bug or not, I leave to others.

The following appears to confirm my analysis with the alert showing before the exception is logged.

if(true) {
    let m = "yo";

    alert(m);
}

console.log(m)
like image 93
Ben Aston Avatar answered Oct 27 '22 15:10

Ben Aston