Dachang Interview questions series – Understanding the scope

Preface:

In JavaScript, there is a feature called Scope.

Scope: Every javascript function is an object. Some properties of the object are accessible, but others are not. Scope is one of them, and it is only accessible by the javascript engine

Without further discussion, a short piece of code will give you a taste of scope:

Example 1.1 function foo () {var a = 1 console.log(a); } foo() console.log(a);Copy the code

What is the value of the two a’s printed out? Are they all 1’s? The first A has a value of 1, and the second A is not defined. At this point, I don’t know if any of you are going to say, well, isn’t a equal to 1? Why do I get an error? This is the scope, we will reveal the secrets ~

First insight into scope

Note: Those with basic knowledge can skip this section directly

1. What is scope

A scope is a set of well-designed rules that store variables and make them easy to find later. Just contact JS white people don’t understand also don’t be nervous, and then look back, after reading still don’t understand the comment area I door one-to-one tutoring hahaha ~ not much to say, then on the code:

Function foo (a) {var b = a * 2 function bar (c) {console.log(a,b,c); } bar( b * 3 ) } foo(2)Copy the code

In the above example, there are three scopes:

  1. The entire global scope, in which only an identifier foo exists.
  2. The scope created by the function foo in which the identifiers a, bar, and b exist.
  3. The scope created by the function bar in which only the c identifier exists.

Here is a classic diagram to understand the scope in Example 1.2:

Different colored bubbles represent different scopes to see if the scopes are more obvious. Includes the individual identifiers that exist in the scope. Scoped bubbles are determined by where their corresponding scoped code block is written, and they are contained level by level. We’ll talk about different types of scopes later, but for now just assume that each function creates a scope bubble.

Here are the two main modes of scoping: the first is the most common, lexical scope used by most programming languages, and will be explained in more detail later. The other is called dynamic scoping, which will also be discussed briefly.

2. What does a scope do?

Scope is the accessibility of certain variables, functions, and objects at run time. What does that mean? Let’s look at some code:

Example 1.3 function foo() {var a = 1} foo() console.log(a); // a is not definedCopy the code

Why is the value of a printed here not defined? Precisely because variable A is defined in function foo, printing variable A in a global context will automatically report an error.

So we can understand what a scope is: a scope is an independent domain that keeps variables from leaking out and being exposed. In other words, the greatest use of a scope is to isolate variables. Variables of the same name in different scopes do not conflict.

Scoped family bucket

We talked about global and function scopes in Examples 1.2 and 1.3, so in this section we’ll take a closer look at scoped buckets.

1. Global scope

What is a global scope? In simple terms, variables or functions defined globally are in the global scope.

So when does a global scope happen? Without further ado, here’s the code:

(1) Global scope is created for variables and functions defined globally.

Var a = 'I am a global variable' // a function foo() {var b = 'I am in a function' // b function bar() {// Function defined in function foo}}Copy the code

The variables a and foo are in the global scope, while the variables B and bar are in the scope generated by foo.

(2) Directly assigned variables

Function foo() {a = 3 var b = 2} foo() {console.log(a); // 3 console.log(b); // b is not definedCopy the code

Why does this variable a have a value here? Because variable A is undeclared and assigned directly, it is automatically put into global scope, while variable B is normally a variable defined in function foo’s scope that is not accessible globally.

The downside of global scope

Example 2.3 var a = 2 var a = 4 console.log(a);Copy the code

As shown above, once the code volume becomes too complex, variable names can be the same, leading to naming conflicts.

2. Function scope

What is a function scope? In simple terms: function scope is when the declaration of a function, will generate a scope, this scope is called the function scope. Code first:

Example 2.4 function foo() {var a = 2 bar() function bar() {var b = 1 console.log(b); // 1 console.log(a); // 2 } console.log(a); // 2 } console.log(a); // a is not defined foo()Copy the code

In this code, the first b is printed as 1 because the variable b is defined in the scope of the function bar, so it normally prints the value of b. The second print why a has the value 2 is that in the function scope, the inner scope can access the variables of the outer scope, while in the fourth print a not defined, the inner variables of the function cannot be accessed from the outside.

3. Block level scope

The block-level scope introduced in ES6 increases the controllability of variables and greatly improves the flexibility of variable use.

So when does a block-level scope occur? – Block-level scopes can be declared with the new let and const commands. The declared variables cannot be accessed outside the scope of the specified block. A block-level scope can be thought of as the region between a pair of curly braces {}. Next up:

(1) block-level scope in functions

Function foo() {let a = 1 console.log(a); // 1 } foo() console.log(a); // a is not definedCopy the code

The variable a declared with let is defined only in function foo and not outside this block-level scope.

(2) Block-level scope in the for loop

For (let I = 0; i < 3; i++) { console.log(i); / / 0} the console. The log (I); // i is not definedCopy the code

Variable I is only defined in the for loop, because declaring variable I with let creates block-level scope, and variable I is not accessible outside the for loop.

Is the variable I declared by the let inside the scope of the parentheses or {} inside the for loop? Let’s look at a piece of code:

For (let I = 0; i < 3; i++) { let i = 'a' console.log(i); // a,a,a }Copy the code

The body of the loop prints three as. This means that in the for loop, variables declared in parentheses with let produce a parent scope and a child scope in the body of the loop. So why can example 2.6 print 1,2, and 3? This is because the inner scope can access the outer scope. In this case, the child scope can access the variable I of the parent scope.

Note: Variables cannot be declared repeatedly

Example 2.8 var a = 2 let a = 1 // Identifier 'a' has already been declaredCopy the code

Repeating a variable declaration in a scope results in an error.

Scope close

After reading the above two sections, I believe you have a basic understanding of scope. In the third section, we will talk about the extension and post-scope. We will update this series in the future.

1. Overview of scope-related knowledge

In this article talked about the concept of scope and only a few different scopes, actually in scope is to store the thing that is called the execution context, as well as the scope of the search rules and enhance the content such as variable, to learning the knowledge of the content must be skilled in scope so behind others published articles to explain in detail the interview series.

2. Scope chain generated by scope

A brief mention of the scope chain produced by many scopes will be made here. This series will separate scopes from other related content, so that parts of each content can be described in more detail.

Scope chain: A collection of execution context objects stored in scope in a chain called scope chain

If you feel that the author has written well, you can move your hands and give a thumb-up and support. You can also pay attention to the author and write a complete set of interview series. If there are any mistakes in this article, you can also discuss them in the comments section.