I have this snippet of code:
4-scoping.js
const thisIsAConst = 50
const constObj = {}
constObj.a = 'a'
let thisIsALet = 51
thisIsALet = 50
let thisIsALet = 50 // errors!
When I run this file, it has an error:
SyntaxError: Identifier 'thisIsALet' has already been declared
I try to modify the file, add a print function to print out thisIsAConst
at the top of the file:
4-scoping.js
console.log(thisIsAConst)
const thisIsAConst = 50
const constObj = {}
constObj.a = 'a'
let thisIsALet = 51
thisIsALet = 50
let thisIsALet = 50 // errors!
Why do I get the same error?
SyntaxError: Identifier 'thisIsALet' has already been declared
What I expect is
ReferenceError: Cannot access 'thisIsAConst' before initialization
Is it the way the JavaScript engine work?
CodePudding user response:
"Identifier has already been declared" is a SyntaxError, it is raised on the parsing stage, before the program even starts running. Reference and Type Errors are runtime errors and are raised during the run time.
If you comment out the second let
in this example, you'll first see the output from the first line, and then the ReferenceError:
console.log('hi')
console.log(c)
const c = 50
let v
let v