I'd like to ask some questions about the scope of JavaScript functions.

A topic about the scope of JS functions

related codes

var xyx = 1;
function fx(){console.log(xyx)}
var xyx = 2;
fx();
The result of the

output is 2.
isn"t it supposed to look from the inside to the outside of the fx function declaration, and then find out that xyx is 1, and then output it? Why did it become 2? Is there something wrong with my understanding? please give me some advice. thank you!


JavaScript is an interpretive language, and the simple understanding is to load the sentence to which it runs (meaning this, but the expression is not entirely accurate). Your code is understood in four steps (the following explanation does not consider the problem of variable promotion for the time being):

var xyx = 1; //xyz1xyz1
function fx(){console.log(xyx)}//fx
var xyx = 2; //xyz2 xyz2
fx();//fxfxxyzxyz2

if you consider variable promotion, the above code is equivalent to:

var xyz; //xyzxyz
xyz = 1;
function fx(){console.log(xyx)}
xyz = 2;
fx();

Doesn't

execute the function body only when the function is called?
according to js execution mechanism

  1. first xyz variable is defined and assigned to 1,
  2. redefine the assignment xyz as 2, overwriting the previous value
  3. call fx (),

so it is 2

  var xyx = 1;
  function fx(){console.log(xyx)  }   // 1
  fx();
  var xyx = 2;

I don't know whether to


 

are you struggling with variable declaration promotion and function declaration promotion?

the effect of declaring promotion is not involved here

The code before the
call is executed, which you can understand as removing the declaration promotion and executing all declarations related to this class once before the function call
.
Menu