JavaScriptFundamental (ES6), part 1
Redeclaring let, const and var in JavaScript
3 Which redeclarations the parser refuses
fairWrite parses(src) that reports whether a snippet is syntactically legal, then use it to compare redeclaring with var, with let, and across two separate blocks.
Stuck? Three hints, smallest first
- 1.
new Function(src)parsessrcwithout running it, so a syntax error surfaces as a thrownSyntaxError. - 2. Return the error’s constructor name so the answer is a comparable string.
- 3. One of these is legal syntax that fails only when it runs. Look for it.
const parses = (src) => {
try { new Function(src); return 'parsed'; } catch (e) { return e.constructor.name; }
};
const cases = [
'var a = 1; var a = 2;',
'let a = 1; let a = 2;',
'let a = 1; var a = 2;',
'{ let a = 1; } { let a = 2; }',
'const a;',
'const a = 1; a = 2;',
];
for (const src of cases) console.log(src.padEnd(30), '->', parses(src));
Output
7 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 7 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('var may be declared twice in one scope', parses('var a = 1; var a = 2;'), 'parsed');
test('let may not', parses('let a = 1; let a = 2;'), 'SyntaxError');
test('nor may a let and a var of the same name collide', parses('let a = 1; var a = 2;'), 'SyntaxError');
test('the same name in two separate blocks is fine', parses('{ let a = 1; } { let a = 2; }'), 'parsed');
test('a const must be given a value on its own line', parses('const a;'), 'SyntaxError');
test('but reassigning one parses, and fails only when it runs', parses('const a = 1; a = 2;'), 'parsed');
test('a parameter may shadow an outer let', parses('let a = 1; function f(a) { return a; }'), 'parsed');
The distinction worth keeping is between an error the parser catches and one the runtime catches. let a; let a; never runs at all — the whole script fails to load. const a = 1; a = 2; loads fine and throws a TypeError when execution reaches the assignment, which means it can hide behind an if and only bite in production.
new Function is the honest way to demonstrate a syntax error without taking the page down with it. It compiles but does not call, so nothing in the snippet executes.