Home Web Front-end JS Tutorial Detailed introduction to the variable promotion mechanism in js

Detailed introduction to the variable promotion mechanism in js

Apr 24, 2020 am 09:24 AM
js variable promotion

Detailed introduction to the variable promotion mechanism in js

Variable promotion

There are two types of variable promotion in JavaScript, variables declared with var and variables declared with function.

Variables declared with var

Let’s first look at the following code, what is the value of a

Code 1

console.log(a);

var a;
Copy after login

According to From the perspective of the past programming language thinking, the code runs from top to bottom. According to this thinking, an error will be reported. Because when the execution reaches the second line, the variable a has not been defined, so the error a is not defined

will be reported. However, in fact the answer is undefined

Okay, with doubts, let’s look at the following code

var a;
console.log(a);
Copy after login

We found that the two pieces of code are the same, so there is a new question, which is It doesn't matter whether there is var a or not. Its answer is always undefined, which creates the illusion that the variable will be improved, so I wrote code 3

code 3

console.log(a);
Copy after login

Okay, it finally An error was reported, so this proves that the javaScript code is not executed from top to bottom, at least on the surface it seems like this.

So let’s look at code 4

Code 4

console.log(a);
var a = 2;
Copy after login

Because the variable is promoted, the answer is 2, but in fact, it is still undefined, why?

At this time we have to ask the compiler, who is responsible for the dirty work such as syntax analysis and code generation.

When the compiler sees var a = 2;, it will treat it as two declarations, var a; and a = 2. The first declaration will be made during the compilation phase, and the second declaration will be Waiting in place for the execution phase.

That is to say, the above code will become the following code

var a;
console.log(a);
a = 2;
Copy after login

So it will end up being undefined

Okay, let me be verbose, look at this code 5

Code 5

a = 2;
var a;
console.log(a);
Copy after login

I think everyone should already know the actual order of execution of this code and its answer. Yes, the answer is 2, but what I want to say is to change the 2nd line is commented out, the answer is still 2, but this has nothing to do with variable promotion. It is a matter of strict mode and non-strict mode. In non-strict mode, developers are allowed not to use keywords to declare variables, but in strict mode This is not possible in mode, it will report an error.

Variables declared with function

Like var, variables declared by function will still be promoted.

log(5);

function log(mes){
  console.log(mes)
}
Copy after login

According to the previous understanding of variable promotion, the real sequence of this code is this,

function log(mes){
  console.log(mes)
}

log(5);
Copy after login

Very good, very correct, then look at the next code

log(5);

var log = function(mes){
  console.log(mes)
}
Copy after login

It reported an error, log is not a function. From here we can see that this kind of function expression will not be promoted. Only function declarations will be promoted. Try adding a line of code console.log at the front. (log), undefined will be output first.

So the real order here is

var log;
log(); //这时候只是声明了log这个变量,并不是函数,却用函数的方法调用它,所以会报错,说这不是一个函数。
log = function(mes){
  console.log(mes)
}
Copy after login

Use var to declare variables in function

Although we know that variables declared with var will be promoted, we don’t know To what extent will it be improved?

Let’s look at a piece of code before this

var a = 4;

function foo(){
  var a = 5;
  console.log(a);

}
foo();

console.log(a)
Copy after login

The answer is 5,4, output 5 first, and then output 4.

Variables declared with var have function scope, so a in foo has no relationship with a outside foo. This situation is exactly what I want.

Change the code again

function foo(){
  a = 5
  console.log(a);
  var a;
}
foo();

console.log(a)
Copy after login

The answer is 5, a is not defined

The 4th line of code outputs 5, and the 9th line reports an error.

In this case, variable promotion will only be promoted to the top of the scope where the variable is located, and will not be promoted to the parent scope.

So we can draw a conclusion: variable promotion will only promote the variable to the top of its own scope

Function priority

Since using var and function The variables have the function of promotion, so what will happen if the same variable is declared with both of them? Well, just look at the title and you will know that the function takes precedence.

Look at the code in detail

foo();

var foo;

function foo(){
  console.log(1)
}

foo = function(){
  console.log(2)
}
Copy after login

The answer is 1

This code actually looks like this

function foo(){
  console.log(1)
}

foo();// 1

foo = function(){
  console.log(2)
}
Copy after login

Look carefully, var foo; is gone, Yep, it was ignored by the engine, which considered it a duplicate declaration and threw it away.

Okay, since variables declared by var are not as good as function declarations, then use function declarations to declare the same variable multiple times.

foo()
function foo(){
  console.log(1);
}
foo()
function foo(){
  console.log(2);
}
foo()
function foo(){
  console.log(3);
}

foo()
Copy after login

foo is declared three times and called four times. The result of each call is 3, so the final function declaration will overwrite the previous function declaration

But var still wants to struggle, I still feel it is necessary to prove my sense of existence.

foo()
function foo(){
  console.log(1);
}
var foo;
foo()
foo = function(){
  console.log(2);
}
foo()
function foo(){
  console.log(3);
}

foo()
Copy after login

Look carefully, the middle part of the code has been changed, outputting 3,3,2,2 in sequence

Although var foo is ignored, the following function is still useful, this code It can be seen as like this

function foo(){
  console.log(3);
}

foo();//3
foo();//3
foo = function(){
  console.log(2);
}
foo();//2
foo();//2
Copy after login

Declare the function inside the ordinary block

Before, the function was declared in the scope, now declare the function inside the block

function foo(){

  console.log(b); // undefined
  b(); //TypeError: b is not a function

  var a = true;

  if(a){
    function b(){
      console.log(2)
    }
    //下面这段代码和上面的结果一样
    // var b = function(){
 //      console.log(2)
 //    }
  }
  //b() --> 这里会被执行

}

foo()
Copy after login

From From the above, b is undefined, which proves that this variable still exists, but it is not a function. This situation is similar to using a function expression.

Summary

1. Promotion is divided into function declaration promotion and variable declaration promotion

2. Use var to declare variables and function to declare functions

3. Variable promotion will promote the variable to the top of its own scope.

4. There is no promotion mechanism for function expressions.

5. Function declaration and variable declaration declare the same identifier at the same time. symbol, the function declaration takes precedence

6. When multiple functions declare the same identifier, the last declaration overwrites the previous declaration

Recommended tutorial: js tutorial

The above is the detailed content of Detailed introduction to the variable promotion mechanism in js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to use JS and Baidu Maps to implement map polygon drawing function How to use JS and Baidu Maps to implement map polygon drawing function Nov 21, 2023 am 10:53 AM

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file

See all articles