0

When I use 'var', below function returns undefined.

var x = 3;

function func(randomize) {
  if (randomize) {
    var x = Math.random();
    return x;
  }
  return x;
}
console.log(func(false)); // undefined

When I use 'let', the same function returns 3.

let x = 3;

function func(randomize) {
  if (randomize) {
    let x = Math.random();
    return x;
  }
  return x;
}
console.log(func(false)); //3

How does compilation works here? Is this because of the lexical environment? I am surprised by the results. Please explain.

  • 2
    Check the live snippets - they appear to produce the same output – CertainPerformance Nov 06 '19 at 02:02
  • Both functions perform the same, it doesn't matter whether they close over a `var`- or `let`-declared variable. – Bergi Nov 06 '19 at 02:03
  • @CertainPerformance Please check the result. They are different. – stack shalini Nov 06 '19 at 02:08
  • 1
    Duplicate of https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var . `let` has block scope, whereas `var` has function scope. Your second `return x` when `var` is used refers to the `var` created inside the function (because function scope), but with `let`, refers to the outer `x` (because block scope) – CertainPerformance Nov 06 '19 at 02:10
  • @CertainPerformance Could you please explain in terms of lexical environment and how does compilation works here? – stack shalini Nov 06 '19 at 02:14
  • @stackshalini Well, the `if` block has its own lexical environment, and the local `x` is only declared inside there. So the `x` in the `return` statement refers to the global `x`. In contrast, the `var x` declares the variable in the lexical environment of the `function`, which is where the `return x` is evaluated in. – Bergi Nov 06 '19 at 02:41

1 Answers1

0

let is a block scope, which means if you declare let x = 3 at global scope, it would be define all thru the scope below the global scope. This is why when you call func(false) since x is in global scope, it is still defined as 3.

var is execution context scope. So when you run the function, func(false), it doesn't have context to x at the run-time of function since x wasn't defined within the function.

tech sf
  • 26
  • 2