An interview question about the scope of the JavaScript variable

  • 2021-01-25 07:05:55
  • OfStack

This site finds this question helpful in understanding the scope of JavaScript, so it is useful for others to review its own solution.

First look at the following questions:


var arr = [1, 2, 3];
  for (var i = 0, j; j = arr[i++];) {
    console.log(j);
  }

  console.log('---------');
  console.log(i);
  console.log('---------');
  console.log(j);
  console.log('---------');

Before we do this, let's review what we know about variable domains in JavaScript.

Global variable (Global)
A global variable is a variable that can be accessed anywhere. There are two cases

Declare outside function, whether or not the var keyword is used
In the function declaration, the var keyword is not used, although the declaration must be executed
Local variables (Local)
Local variables can only be accessed inside the declared function
Declare in function, using the var keyword
Two caveats

First look at the code:


alert(i); //  The output  undefined
 
 for (var i = 0; i < 1; i++){};
 
 alert(i); //  The output 1

JavaScript does not have a statement scope. Variables defined within a statement will spread outside the statement. In our example, i is declared in an for statement, but is still accessible outside of an for statement
i is accessed before the for statement, but not yet assigned
So let's do the problem

i++ is self-added after i use:

The first time, j=arr[0], then i=1, console.log(j) output 1

j=arr[1], then i=2, ocnsole.log(j) outputs 2

j=arr[2], then i=3, ocnsole.log(j) outputs 3

The fourth time (does not meet the conditions of for), j=arr[3] is undefined, then i=4, ocnsole.log(j) has no output, exit the for cycle

console.log(i) output 4, console.log(j) output undefined

The final output is as follows:


2
---------
---------
undefined
---------

In view of the above analysis and results, presumably everyone has been clear about it, and then let's start to use 1 against 3.

Let's go to number 1
Topic:
var arr = [1, 2, 3];


  for (var i = 0, j; j = arr[++i];) {
    console.log(j);
  }

  console.log('---------');
  console.log(i);
  console.log('---------');
  console.log(j);
  console.log('---------');

The answer:


2
3
---------
3
---------
undefined
---------

Let's go to number 2
Topic:


function xxx() {
    var arr = [1, 2, 3];
    for (var i = 0, j; j = arr[i++];) {
      console.log(j);
    }
  }
  xxx();

  console.log('---------');
  console.log(i);
  console.log('---------');
  console.log(j);
  console.log('---------');

The answer:


1
2
3
---------
 Error: Uncaught ReferenceError: i is not defined

I hope it will help you understand the scope of JavaScript.


Related articles: