javascriptlexical-scope

lexical scope in Javascript issue


in the following code snippet, I defined "bob" first, but the output is "alice:1 hi alice", I don't know why?

let user = "";
function greet() {
  console.count(user);
  return `hi ${user}`;
}
user = "bob";
user = "alice";
console.log(greet());//alice:1 hi alice

Solution

  • The output is hi alice because, by the time greet() is executed, the variable is reassigned to alice.

    If you want the count to reflect the bob value, you should call greet() any time before its value is changed.

    Demo:

    let user = "";
    function greet() {
      console.count(user);
      return `hi ${user}`;
    }
    
    user = "bob";
    console.log(greet()); //hi bob
    
    user = "alice";
    console.log(greet()); //hi alice