Today I run into a weird JS bug, working with const
inside a try/catch block, and I'd like to better understand what is causing it.
Let's look at a code example, that is worth more than a thousand words:
try {
const FOO = 'bar';
console.log('inside:', FOO);
} catch (e) {}
console.log('outside:', FOO);
This will log:
inside: bar
outside: bar
If we switch to "strict mode" though:
'use strict';
try {
const FOO = 'bar';
console.log('inside:', FOO);
} catch (e) {}
console.log('outside:', FOO);
Now the same code produces an error:
ReferenceError: FOO is not defined
If we change const
with var
though:
'use strict';
try {
var foo = 'bar';
console.log('inside:', foo);
} catch (e) {}
console.log('outside:', foo);
Then it all works fine again, even in "strict mode":
inside: bar
outside: bar
Can anyone please help me understand why the const
assignment is not working inside a try/catch block in "strict mode"?
Thanks!
Your JavaScript runtime has a partial implementation of ES6
const
.ReferenceError
is the expected behaviour for your first example, becauseconst
is block scoped and you accessFOO
outside the definingtry
block.The engine you are using supports the
const
syntax, but it only applies block scoping semantics in strict mode.The current stable Chrome (46) does this. Chrome 48, however, applies block scope with or without strict mode.
var
is not block scoped, so your last example works as expected.const
, as defined by ECMAScript 6, is a block-level variable declaration. You get aReferenceError
because it's not in scope outside of thetry
.However,
const
was introduced in some engines long before ES6, as a immutable counterpart tovar
, with function-level scope behaviour (and without TDZ). If you're in sloppy mode (which you should not be), you might still experience this as part of your browser's legacy support.