Skip to content
Advertisement

How does work LexicalEnvironment and VariableEnvironment?

In first example, I expected to see undefined instead 3. Why does console show 3 in first example? Is it related with LexicalEnvironment and VariableEnvironment?

function test(num) {
  var num
  console.log(num) // 3
}
test(3) 

and

function test(num) {
  var num = 5
  console.log(num) // 5
}
test(3) 

Advertisement

Answer

Why does console show 3 in first example?

num is already declared in the environment, as parameter. Hence the var num statement is ignored.

The same happens in the second example. But here you have an assignment as well. Variable declarations with initial values are basically evaluated in two separate steps:

  1. As part of setting up the new function lexical environment, all declared variables are collected. Because there is already a parameter with the same name, the variable declaration is ignored.

  2. Then every statement of the function body is evaluated, and in that phase the assignment (num = 5) takes pace.

Is it related with LexicalEnvironment and VariableEnvironment?

A LexicalEnvironment is a construct for associating identifier names with values, so yes, it’s certainly related.

However, how a function body is evaluated is defined in FunctionDeclarationInstantiation. Ignoring variable declarations which already exists as parameter names is defined in step 27.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement