【发布时间】:2020-02-28 09:36:58
【问题描述】:
I try writing the following lines in the console one by one
let x = y //throws error "Uncaught ReferenceError: y is not defined"
console.log(x) //throws error "ReferenceError: x is not defined"
let x = 3; //gives error "Uncaught SyntaxError: Identifier 'x' has already been declared"
x = 3 //ReferenceError: x is not defined
Now problem is that how can be a variablenot definedandhas been declaredat the same time. Is there any difference between both.
【问题讨论】:
-
It's a poor use of language by the browser consoles. Those
ReferenceErrors should really say the variable is not "declared", but afaik it's always been thus. -
From link:When there's assignment, the right-hand side is parsed first; if the right-hand side throws an error, it never gets to the left-hand side, and the variable declared with let never gets properly initialized; it'll stay in the demilitarized zone / temporal dead zone forever(and you can't re-declare a variable that's already been declared, even though the attempted assignment during initialization threw an error).
-
There's a big difference betweendeclarationandinitialization. In your first line
x = y, you declaredxand tried to assignyto it, which isundefined, soxis declared and will be initialized withundefinedasvalue. That's why you gotxis already declared. -
@MaheerAli
let x = 3;will throw error as you have already declared it. Butx=3should not throw error, unless you define it asconst -
Being declared doesn't mean it will be initialized to undefined. Are variables declared with let or const not hoisted in ES6?
标签: javascript variables