2

I have trouble understand the let declaration in javascript. When I assign the variable to something syntactical incorrect ( and give error), it still declare the variable. But I can not change value or access it. For example:

let test = abc;  //reference error: abc not defined. Expected
let test = 5; //syntax error: test already "declare"
test = 5; //reference error: test not defined
alert(test); //reference error: test not defined

So even when the code occurs error, the variable is still declared and unchangeable?

Anh
  • 85
  • 2
  • 11
  • That's interesting. Happens in Chrome, not in Firefox. – Alexander O'Mara May 12 '19 at 03:24
  • 1
    The ECMA documentation states "The variables are created when their containing Lexical Environment is instantiated but may not be accessed in any way until the variable’s LexicalBinding is evaluated." So I think the lexical environment is first instantiated and the variable is created but since there is no way to evaluate its binding due to the first assignment error, everything onwards is an error. – Andrés Hernández May 12 '19 at 03:31
  • This is because of hoisting – adiga May 12 '19 at 03:40

1 Answers1

0

The first let test tries to create a globally scoped variable name test.

The interpreter sees the request for a new variable and creates room for it, sees the name of the variable and labels it, then sees the initial value and goes, "Wait a minute: abc is not a thing!" and ignores the assignment.

You can think of let varname = value; as actually two commands together:

let varname;

then

let varname = value;

You can test this by seeing that let the_var; in your console will instantiate a variable with an undefined value called the_var.

Jesse Lawson
  • 715
  • 8
  • 13
  • I thought the same but it does not seem so. For example: ```let test2;``` then ```test2 = 5 ```, it is valid. But in my original example, ```test = 5 ``` will result reference error. – Anh May 12 '19 at 03:37
  • 1
    This is not the same. `let test2;` causes `test2` to be created with value of `undefined`. `test2 = 5;` is valid because test2 was already created. From the ECMA Documentation (someone else linked this, too): "The variables are created when their containing Lexical Environment is instantiated but may not be accessed in any way until the variable’s LexicalBinding is evaluated." [Read this answer](https://stackoverflow.com/questions/54979906/is-there-any-difference-between-declared-and-defined-variable) for more. – Jesse Lawson May 12 '19 at 03:42