Introduction to the new variable declaration method in ES6 (with code)
This article brings you an introduction to the new variable declaration method in ES6 (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
In ES5, there are only three types of variable declarations: var, function, and implicit declaration. In ES6, four types are added: let, const, import, and class.
1. let
1.1 Block-level scope
The scope of the variable declared by let is the block-level scope (this feature is somewhat similar to Backend language), ES5 does not have block-level scope, only function scope and global scope.
{ let a = 'ES6'; var b = 'ES5'; } console.log(b) // ES5 console.log(a) // ReferenceError: a is not defined.
So what are the benefits of let’s block-level scope?
let is very suitable for block-level scope inside a for loop. The for loop body in JS is special. Each execution is a new independent block scope. After the variables declared with let are passed into the scope of the for loop body, they will not change and will not be affected by the outside world. Look at a common interview question:
for (var i = 0; i <p>Change var to let statement: </p><pre class="brush:php;toolbar:false">for (let i = 0; i <p>1.2 Temporary Dead Zone </p><p>In a block-level scope , variables only exist. Once a variable is declared with let in a block-level scope, the variable uniquely belongs to this block-level scope and is not affected by external variables, as shown below. </p><pre class="brush:php;toolbar:false">var tmp = 'bread and dream'; if(true){ tmp = 'dream or bread'; //ReferenceError let tmp; }
In this example, the assignment of tmp = 'dream or bread' will report an error because let in the if block declares the tmp variable, causing the tmp to be bound to this scope and let to temporarily die. As a result, it cannot be used before declaration, so assigning a value to a variable before declaration will cause an error.
The essence of the temporary dead zone is that as soon as the current scope is entered, the variable to be used already exists, but cannot be obtained. Only when the line of code that declares the variable appears can the variable be obtained and used. variable.
The significance of the temporary dead zone is also to allow us to standardize the code and place the declaration of all variables at the beginning of the scope.
1.3 Repeated declarations are not allowed
(1) In the same scope, when using let to declare a variable, it is only allowed to be declared once, but var can be declared multiple times. Everyone knows that multiple declarations in ES5 will cause variable coverage and no error will be reported, which makes debugging more difficult, but let can directly kill this problem in the cradle because it will directly report an error.
// 不报错 function demo() { var a = 'bread and dream'; var a = 'dream or bread'; } // 报错,Duplicate declaration "a" function demo() { let a = 'bread and dream'; var a = 'dream or bread'; } // 报错,Duplicate declaration "a" function demo() { let a = 'bread and dream'; let a = 'dream or bread'; }
(2) Parameters cannot be redeclared inside a function:
function demo1(arg) { let arg; // 报错 } demo1() function demo2(arg) { { let arg; // 不报错 } } demo2()
2. const
2.1 is used to declare constants
## Constants declared with #const are not allowed to be changed and are read-only attributes. This means that constants must be assigned a value when they are declared. If they are declared without assignment, an error will be reported. Usually constants are named with capital letters.const Person; // 错误,必须初始化 const Person = 'bread and dream';// 正确 const Person2 = 'no'; Person2 = 'dream or bread'; //报错,不能重新赋值This has two benefits: First, people reading the code will immediately realize that this value should not be modified, and second, it prevents errors caused by inadvertently modifying the variable value. For example, when we use some modules of nodejs, we only use the corresponding modules (such as http module), but do not need to modify the nodejs module. At this time, we can declare it as const, which increases the readability of the code and avoids errors. 2.2 Supports block-level scopeconst is similar to let and also supports block-level scope.
if (true) { const MIN = 5; } MIN // Uncaught ReferenceError: MIN is not defined2.3 Does not support variable promotion and has a temporary dead zoneConsts declared by const are not promoted. They also have a temporary dead zone and can only be used after the declared position.
if (true) { console.log(MIN); // ReferenceError const MIN = 5; }2.4 Special casesIf the declared constant is an object, then the object itself is not allowed to be reassigned, but the properties of the object can be assigned.
const obj = {}; obj.a = 'xiao hua'; console.log(obj.a); //'xiao hua'In fact, what const can guarantee is not that the value of the variable cannot be changed, but that the data stored in the memory address pointed to by the variable cannot be changed. For simple types of data (numeric values, strings, Boolean values), the value is stored at the memory address pointed to by the variable, so it is equivalent to a constant. But for composite type data (mainly objects and arrays), the memory address pointed to by the variable only stores a pointer to the actual data. As for whether the data structure it points to is variable, it is completely out of control. Therefore, you must be very careful when declaring an object as a constant. If you want to completely freeze the object (its properties cannot be modified), you should use the Object.freeze(obj) method. The same goes for arrays.
3. import
ES6 uses import instead of require such as node to import modules.import {$} from './jquery.js'$The object is the object exposed by export in jquery. If you want to rename the input variable, use the as keyword in the import command to rename the input variable.
import { JQ as $ } from './jquery.js';Note that the import command has a promotion effect and will be promoted to the head of the entire module and executed first.
4. class
ES6 introduces the concept of class and the keyword class. The essence of a class is still a function object. First define a class://定义类 class Animal { constructor(name, age) { this.name = name; this.age = age; } setSex(_sex) { this.sex=_sex; } }The constructor method is the constructor method, which is the main body of the function object in the ES5 era, and the this keyword represents the instance object. The above class can also be changed to ES5 writing:
function Animal(name, age){ this.name = name; this.age = age; } Animal.prototype.setSex = function (_sex) { this.sex=_sex; }In fact, the characteristics of most classes can be deduced through the previous function objects and prototypes.
生成类的实例对象的写法,与ES5通过构造函数生成对象完全一样,也是使用new命令。
class Animal {} let dog = new Animal();
在类的实例上面调用方法,其实就是调用原型上的方法,因为类上的方法其实都是添加在原型上。
Class其实就是一个function,但是有一点不同,Class不存在变量提升,也就是说Class声明定义必须在使用之前。
5.总结
在ES6之前,JavaScript是没有块级作用域的,如果在块内使用var声明一个变量,它在代码块外面仍旧是可见的。ES6规范给开发者带来了块级作用域,let和const都添加了块级作用域,使得JS更严谨和规范。
let 与 const 相同点:
块级作用域
有暂时性死区
约束了变量提升
禁止重复声明变量
let 与 const不同点:
const声明的变量不能重新赋值,也是由于这个规则,const变量声明时必须初始化,不能留到以后赋值。
合理的使用ES6新的声明方式,不管是面试还是工作中都有实际的应用,尤其是工作中,大家一定要尽量的多使用新的声明方式,不但可以让代码更规范,更可以避免不必要的bug,浪费调试时间,进而提高工作效率。
本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的JavaScript视频教程栏目!
The above is the detailed content of Introduction to the new variable declaration method in ES6 (with code). For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools
