Wednesday, 31 May 2017

What state is kept between JavaScript code blocks?

I read (from "JavaScript, the good parts") that JavaScript has no block scopes, and it is even suggested to declare variables inside a function at its very beginning instead of inside { }'s to avoid confusion.

However, I am confused by an example (simplified here) that I just encountered and tested using babel-node --presets es2015:

> {const a = 1;}; {const a = 2;};
undefined
> a;
1

Here, the two const variable assignments made in one line would generate an error if they hadn't been enclosed in blocks {} as discussed in my previous question What state is kept between JavaScript lines? (so that separate transpilation shouldn't be an issue).

However, when used in code blocks, no error is generated. And as shown above, the second assignment seems to have no effect at all.

The behavior in node is also interesting,

> {const a = 1;}; {const a = 2;};
undefined
> a;
ReferenceError: a is not defined
...

It's as if the two code blocks didn't happen, a is not defined. So:

Why is enclosing statements in code blocks induce different behavior above?

What's remembered/forgotten between the code blocks?

Which behavior among babel-node and node is correct or standard-compliant?

FYI, versions are:

$ node --version
v7.10.0
~$ babel-node --version
6.24.1



via tinlyx

No comments:

Post a Comment