Home  >  Article  >  Web Front-end  >  A brief explanation of function scope and block-level scope in JavaScript

A brief explanation of function scope and block-level scope in JavaScript

不言
不言Original
2018-08-01 16:13:321997browse

This article introduces to you a brief explanation of function scope and block-level scope in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Function-level scope

Let’s look at a piece of code first

var a = true;

function hoisting(){
    if(!a){
        var a = 2;
    }
    console.log(a)
}

hoisting();
// 最终结果:2

The logic of this code is

  1. Will first look for variables in the current function domain .

  2. If it exists, declare the variable header first. If it does not exist, search

  3. from the parent again until it is found.

Then we can rewrite it as

var a; // 变量声明 
a = true; // 变量定义

function hoisting(){
    var a; // 变量声明
    if(!a){
        a = 2; //变量定义
    }
    console.log(a) // 先从自身函数域开始查找,找不到再去父作用域
}

hoisting();

Javascript variables exist with functions as scope, and when they cannot be found locally, they will go to the parent level to find them.

2. Solution: Closure IIFE

may not have much to do with this article~~, the main thing is that closure constructs a new function domain.

Immediately Invoked Function Expression

His function is to assign a value to the variable before it is called

var a = (function(){
    var a = 3
    return a
}())

3. Solution: let, const

The main function of let and const is to adjust the original function-level scope of JavaScript to the block-level scope

let a = 2;

function block(){
    if(!a){
        let a =1
    }
    console.log(a)
}

block() // 2

At this time, the scope of the function is divided Smaller, at the block level.

We can divide the code into three blocks

  • if block

  • block block

  • window block

Okay, now what will happen if we rewrite the function?

let a = 0;

function block(){
    if(!a){
        let a =1
    }
    console.log(a)
}

block() // 0

The final result is 0, when a cannot be found in the current block Sometimes it will go to the parent block to search, and the final value is 0

And the variables in the if block are only valid within the block

Recommended related articles:

JS object-oriented Encapsulated parsing in programming

How is jQuery’s self-calling anonymous function called?

The above is the detailed content of A brief explanation of function scope and block-level scope in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn