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!