search
HomeWeb Front-endFront-end Q&AWill es6 import promote variables?
Will es6 import promote variables?Jan 18, 2023 pm 07:44 PM
javascriptes6variable promotion

ES6 import will cause variable promotion. Variable hoisting is the promotion of a variable declaration to the very beginning of its scope. js has to go through the compilation and execution phases. During the compilation phase, all variable declarations will be collected and variables declared in advance, while other statements will not change their order. Therefore, during the compilation phase, the first step is already is executed, and the second part is executed only when the statement is executed in the execution phase.

Will es6 import promote variables?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

Variable promotion

JavaScript is a single-threaded language, so execution must be performed in order. But it is not analyzed and executed line by line, but analyzed and executed piece by piece. The compilation phase will be performed first and then the execution phase. During the compilation phase, a few milliseconds before the code is actually executed, all variable and function declarations are detected and added to memory within a JavaScript data structure called Lexical Environment. So these variables and functions can be used before they are actually declared.

Let’s start with a simple example:

 a = 2;
 var a;
 console.log(a);

What will the above code output? If this code is executed from top to bottom, it will definitely output undefined, but JavaScript is not A language that executes top-down. The output of this code is 2, is it unexpected? So, why is this happening? The key point lies in--Variable promotion. It will raise the declarations of all variables in the current scope to the top of the program. Therefore, the above code is equivalent to the following code. Does this make it clearer?

 var a;
 a = 2;
 console.log(a);

Then let’s look at another example:

 console.log(a);
 var a = 2;

What will this code output? Output 2? In fact, this code will output undefined. This is why? As I just said, JavaScript will promote the declaration of variables to the top, but the assignment statement will not be promoted. For js, var a = 2 is divided into two-step parsing:

var a;
a = 2;

And js will only promote the sentence var a, so the statement just now is equivalent to:

 var a;
 console.log(a);
 a = 2;

So, why is there variable promotion?

Why does the phenomenon of variable promotion occur? Because js, like other languages, has to go through the compilation and execution stages. When js is in the compilation stage, it will collect all variable declarations and declare variables in advance, and other statements will not change their order. Therefore, during the compilation stage, the first step has been executed, and the second The part is executed only when the statement is executed in the execution phase.

ES6 import variable promotion

ES6 import will cause variable promotion.

For example, in the following test code,

// a.js
console.log('I am a.js...')
import { foo } from './b.js';
console.log(foo);
// b.js
console.log('I am b.js...')
export let foo = 1;

runs a.js,

// node -r esm a.js 
I am b.js...
I am a.js...
1

The printed result is that 'I am b.js...' appears first , and then 'I am a.js...' appears again. This is the phenomenon of variable promotion.

This is because ES6 implements the module function at the language standard level, so when a.js is pre-compiled and the keyword import is found, b.js is loaded first, so 'I am b. js...'.

The whole process is that

Will es6 import promote variables?

The generation of variable promotion is actually related to the creation process of variable objects.

Variable object creation process

The creation of a variable object (Variable Object) goes through the following steps in sequence.

Will es6 import promote variables?

  • Check the function declaration of the current context, that is, the function declared using the function keyword. Create an attribute with the function name in the variable object, and the attribute value is a reference to the memory address where the function is located. If the function name attribute already exists, the attribute will be overwritten by the new reference.

  • Check the variable declarations in the current context. Whenever a variable declaration is found, create an attribute with the variable name in the variable object, and the attribute value is undefined. If the attribute of the variable name already exists, in order to prevent the function with the same name from being modified to undefined, it will be skipped directly and the original attribute value will not be modified.

The function statement will have a higher priority than the var statement.

function test() {
  console.log(a);
  console.log(foo());

  var a = 1;
  function foo() {
    return 2;
  }
}

test();

Start understanding directly from the execution context of test().

// 创建过程
testEC = {
    // 变量对象
    VO: {},
    // 作用域链
    scopeChain: {}
}

// VO 为 Variable Object 的缩写,即变量对象
VO = {
    arguments: {...},
    foo: <foo reference>    // 表示foo的地址引用
    a: undefined
}

The result of test() execution is,

// node -r esm demo01.js 
undefined
2

In fact, the above code demo01.js becomes this execution sequence,

function test() {
    function foo() {
        return 2;
    }
    var a;
    console.log(a);
    console.log(foo());
    a = 1;
}
test();

[Related recommendations: javascript learning tutorial

The above is the detailed content of Will es6 import promote variables?. 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
es6怎么判断是否为数组es6怎么判断是否为数组Apr 25, 2022 pm 06:43 PM

在es6中,可以利用“Array.isArray()”方法判断对象是否为数组,若判断的对象是数组,返回的结果是true,若判断对象不是数组,返回的结果是false,语法为“Array.isArray(需要检测的js对象)”。

es6中遍历跟迭代的区别是什么es6中遍历跟迭代的区别是什么Apr 26, 2022 pm 02:57 PM

es6中遍历跟迭代的区别是:遍历强调的是要把整个数据依次全部取出来,是访问数据结构的所有元素;而迭代虽然也是依次取出数据,但是并不保证取多少,也不保证把所有的数据取完,是遍历的一种形式。

es6中怎么判断两个对象是否相等es6中怎么判断两个对象是否相等Apr 19, 2022 pm 03:34 PM

在es6中,可用Object对象的is()方法来判断两个对象是否相等,该方法检测两个变量的值是否为同一个值,判断两个对象的引用地址是否一致,语法“Object.is(对象1,对象2)”;该方法会返回布尔值,若返回true则表示两个对象相等。

es6怎么将数字转为字符串es6怎么将数字转为字符串Apr 19, 2022 pm 06:38 PM

转换方法:1、利用“+”给数字拼接一个空字符,语法“数字+""”;2、使用String(),可把对象的值转换为字符串,语法“String(数字对象)”;3、用toString(),可返回数字的字符串表示,语法“数字.toString()”。

es6 import会变量提升吗es6 import会变量提升吗Jan 18, 2023 pm 07:44 PM

ES6 import会产生变量提升的现象。变量提升是将变量声明提升到它所在作用域的最开始的部分。js要经历编译跟执行阶段,在编译阶段的时候,会搜集所有的变量声明并且提前声明变量,而其他的语句都不会改变他们的顺序,因此,在编译阶段的时候,第一步就已经执行了,而第二部则是在执行阶段执行到该语句的时候才执行。

es6中assign的用法是什么es6中assign的用法是什么May 05, 2022 pm 02:25 PM

在es6中,assign用于对象的合并,可以将源对象的所有可枚举属性复制到目标对象;若目标对象与源对象有同名属性,或多个源对象有同名属性,则后面的属性会覆盖前面的属性,语法为“Object.assign(...)”

es6怎么改变数组数据es6怎么改变数组数据Apr 26, 2022 am 10:08 AM

改变方法:1、利用splice()方法修改,该方法可以直接修改原数组的内容,语法为“数组.splice(开始位置,修改个数,修改后的值)”;2、利用下标访问数组元素,并重新赋值来修改数组数据,语法为“数组[下标值]=修改后的值;”。

sort排序是es6中的吗sort排序是es6中的吗Apr 25, 2022 pm 03:30 PM

sort排序是es6中的;sort排序是es6中用于对数组的元素进行排序的方法,该方法默认不传参,按照字符编码顺序进行排序,排序顺序可以是字母或数字,并按升序或降序,语法为“array.sort(callback(a,b))”。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools