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:
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?
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With