Global variables and implicitly declared global variables.

is as follows: it"s a piece of code on a MDN

var x = 0;
function f(){
  var x = y = 1; // xy
}
f();
console.log(x, y); // 0, 1
// x
// y

Q:
1. Why the result is 0BI 1
2. Why does the code comment say, "x is declared inside the function, y is not!"
3. What is an implicitly declared global variable

based on the above, I changed the code as follows:

function f(){var a = b = 1; }
f();
console.log(b);// 1
console.log(a);// a is not defined

ask: why an is not defined

the students who are in trouble will help me to answer it. Thank you!

Mar.18,2021

1. Why the result is 0BI 1

two points.
1. var x = y = 1 is equivalent to var x; x = y = 1
, that is, the declaration of y is skipped, and the global variable y
2. console.log (x code y) are all global variables, the answer is obvious

.
2. Why does the code comment say, "x is declared inside the function, y is not!"

for reasons, see the first point in the previous answer

3. What is an implicitly declared global variable

except for variables of the host environment itself, all other global variables not created by var/let/const are "implicitly declared global variables"

ask: why an is not defined

still see the first item in the first answer. a is a local variable of the function f and cannot be accessed outside the local scope

.

there are many strange phenomena in javascript. In view of these problems, we should try our best to avoid them.


variables defined by var are limited to the current scope and subscope.

your code can be equivalent to:

var x = 0;
var ccc = 3;

function f(){
  // yvary
  y = 1;
  // xvar`var x_new_define = y`
  // xxx
  var x = y;
  // z
  var z = 1;

  // varcccvar
  ccc = 5;
}

f();

console.log(x, y); // 0, 1
// z
console.log(z); // throw Error

console.log(ccc); // 5

generally speaking, you still don't understand the basic parts of js. It is recommended to read more books, especially scope-related knowledge points, and then write a few small demo to try

.
Menu