돌아가기
이 글은 다음 언어로만 작성되어 있습니다. عربي, English, Español, فارسی, Français, Indonesia, 日本語, Русский, Українська, 简体中文. 한국어 번역에 참여해주세요.

Does a function pickup latest changes?

중요도: 5

The function sayHi uses an external variable name. When the function runs, which value is it going to use?

let name = "John";

function sayHi() {
  alert("Hi, " + name);
}

name = "Pete";

sayHi(); // what will it show: "John" or "Pete"?

Such situations are common both in browser and server-side development. A function may be scheduled to execute later than it is created, for instance after a user action or a network request.

So, the question is: does it pick up the latest changes?

The answer is: Pete.

A function gets outer variables as they are now, it uses the most recent values.

Old variable values are not saved anywhere. When a function wants a variable, it takes the current value from its own Lexical Environment or the outer one.