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
2
Answers
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:
in this code snippet, we have a variable and a function, as much as it is related to lexical scope, the variable is defined outside the function , it means all the code outside the function and inside the function has access to the variable, that is all about scope.
but about the value of the user, since you call the function after the variable was assigned to alice so what it prints is alice