Home > other >  Why does the Javascript engine ignore the first error which prints a const variable before it's
Why does the Javascript engine ignore the first error which prints a const variable before it's

Time:08-07

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

  • Related