search
HomeWeb Front-endJS TutorialIntroduction 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 scope

const is similar to let and also supports block-level scope.

if (true) {
  const MIN = 5;
}

MIN // Uncaught ReferenceError: MIN is not defined
2.3 Does not support variable promotion and has a temporary dead zone

Consts 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 cases

If 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!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)