search
HomeWeb Front-endJS TutorialA look at the five most important features of JavaScript ES6

A look at the five most important features of JavaScript ES6

JavaScript ES6 adds a host of new language features, some more groundbreaking and more widely available than others. Features like ES6 classes, while novel, are really just syntactic sugar on top of the existing methods of creating classes in JavaScript. Functions like generators, although very powerful, are reserved for targeted tasks.

From working on different JavaScript-related projects over the past 12 months, I have found 5 ES6 features that are indispensable because they really simplify the way common JavaScript tasks are done. Your top 5 may be different from mine, and if so, I hope you'll share them in the comments section at the end.

Let’s get started!

  1. Arrow Functions
  2. Promises
  3. Async Functions
  4. Destructuring
  5. Default and Rest Parameters

1) JavaScript Arrow Function

One of my favorite new features in ES6 JavaScript is not a completely new feature. But a new syntax that makes me smile every time I use it. I'm talking about arrow functions, which provide an extremely elegant and concise way to define anonymous functions.

In short, the arrow function loses the keyword function, and then uses an arrow => to separate the parameter part and function body of an anonymous function :

(x, y) => x * y;

This is equivalent to:

function(x, y){
    return x * y;
}

or:

(x, y) => {
    var factor = 5;
    var growth = (x-y) * factor;
}

is exactly equivalent to:

function(x, y){
    var factor = 5;
    var growth = (x-y) * factor;
}

When using traditional anonymous functions, arrow functions It also eliminates a key source of errors, namely the value of the this object within a function. With arrow functions, this is based on lexical binding, which is just a fancy way of saying that its value is bound to the parent scope and never changes. If an arrow function is defined in a custom object countup, the this value will undoubtedly point to countup. For example:

var countup = {
    counter: 15,

    start:function(){
        window.addEventListener('click', () => {
            alert(this.counter) // correctly alerts 15 due to lexical binding of this
        })
    }
};

countup.start();

Compared with traditional anonymous functions, where the value of this changes depends on the context in which it is defined. When trying to reference this.counter in the above example, the result will be undefined, a behavior that may confuse many people who are not familiar with the complexities of dynamic binding. Using arrow functions, the value of this is always predictable and easy to infer.

For a detailed explanation of arrow functions, please see "Overview of JavaScript Arrow Functions".

2) JavaScript Promises

JavaScript ES6 Promises makes the processing of asynchronous tasks become Linear, this is a task in most modern web applications. Instead of relying on callback functions - popularized by JavaScript frameworks such as jQuery. JavaScript Promises use a central, intuitive mechanism for tracking and responding to asynchronous events. Not only does it make debugging asynchronous code easier, it also makes writing it a joy.

All JavaScript Promises start and end with the Promise() constructor:

const mypromise = new Promise(function(resolve, reject){
 // 在这编写异步代码
 // 调用 resolve() 来表示任务成功完成
 // 调用 reject() 来表示任务失败
})

Internally use resolve() and reject() method, when a Promise is completed or rejected, we can send a signal to a Promise object respectively. The then() and catch() methods can then be called to handle the work after the Promise is completed or rejected.

I use the following variant of Promise injected into the XMLHttpRequest function to retrieve the contents of external files one by one:

function getasync(url) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()
        xhr.open("GET", url)
        xhr.onload = () => resolve(xhr.responseText)
        xhr.onerror = () => reject(xhr.statusText)
        xhr.send()
    })
}

getasync('test.txt').then((msg) => {
    console.log(msg) // echos contents of text.txt
    return getasync('test2.txt')
}).then((msg) => {
    console.log(msg) // echos contents of text2.txt
    return getasync('test3.txt')
}).then((msg) => {
    console.log(msg) // echos contents of text3.txt
})

To master the key points of JavaScript Promises, such as Promise chaining and parallel execution Promise, please read "Beginner's Guide to Promises".

3) JavaScript asynchronous functions

In addition to JavaScript Promise, asynchronous functions further rewrite the traditional asynchronous code structure to make it more readable sex. Whenever I show code with async programming capabilities to clients, the first reaction is always surprise, followed by curiosity to understand how it works.

An asynchronous function consists of two parts:

1) A regular function prefixed with async

async function fetchdata(url){
    // Do something
    // Always returns a promise
}

2) In the asynchronous function (Async function), use the await keyword to call the asynchronous operation function

An example is worth a thousand words. The following is a Promise rewritten based on the above example to use Async functions instead:

function getasync(url) { // same as original function
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()
        xhr.open("GET", url)
        xhr.onload = () => resolve(xhr.responseText)
        xhr.onerror = () => reject(xhr.statusText)
        xhr.send()
    })
}

async function fetchdata(){ // main Async function
    var text1 = await getasync('test.txt')
    console.log(text1)
    var text2 = await getasync('test2.txt')
    console.log(text2)
    var text3 = await getasync('test3.txt')
    console.log(text3)
    return "Finished"
}

fetchdata().then((msg) =>{
    console.log(msg) // logs "finished"
})

When the above example is run, it will output "test.txt", "test2.txt", "test3 .txt" and finally "Finished".

As you can see, in the asynchronous function, we treat the asynchronous function getasync() as a synchronous function call – there is no then() method or callback function Notification to proceed to next step. Whenever the keyword await is encountered, execution is paused until getasync() resolves before moving to the next line in the async function. The result is the same as purely Promise-based, using a bunch of then methods.

要掌握异步函数,包括如何 await 并行执行函数,请阅读 “Introduction to JavaScript Async Functions- Promises simplified”

4) JavaScript 解构

除了箭头函数,这是我每天使用最多的 ES6 功能。ES6 解构并非一个新功能,而是一个新的赋值语法,可以让您快速解压缩对象属性和数组中的值,并将它们分配给各个变量。

var profile = {name:'George', age:39, hobby:'Tennis'}
var {name, hobby} = profile // destructure profile object
console.log(name) // "George"
console.log(hobby) // "Tennis"

这里我用解构快速提取 profile 对象的 namehobby 属性 。

使用别名,你可以使用与你正在提取值的对象属性不同的变量名:

var profile = {name:'George', age:39, hobby:'Tennis'}
var {name:n, hobby:h} = profile // destructure profile object
console.log(n) // "George"
console.log(h) // "Tennis"

嵌套对象解构

解构也可以与嵌套对象一起工作,我一直使用它来快速解开来自复杂的JSON请求的值:

var jsondata = {
    title: 'Top 5 JavaScript ES6 Features',
    Details: {
        date: {
            created: '2017/09/19',
            modified: '2017/09/20',
        },
        Category: 'JavaScript',
    },
    url: '/top-5-es6-features/'
};

var {title, Details: {date: {created, modified}}} = jsondata
console.log(title) // 'Top 5 JavaScript ES6 Features'
console.log(created) // '2017/09/19'
console.log(modified) // '2017/09/20'

解构数组

数组的解构与在对象上的工作方式类似,除了左边的花括号使用方括号代替:

var soccerteam = ['George', 'Dennis', 'Sandy']
var [a, b] = soccerteam // destructure soccerteam array
console.log(a) // "George"
console.log(b) // "Dennis"

你可以跳过某些数组元素,通过使用逗号(,):

var soccerteam = ['George', 'Dennis', 'Sandy']
var [a,,b] = soccerteam // destructure soccerteam array
console.log(a) // "George"
console.log(b) // "Sandy"

对我而言,解构消除了传统方式提取和分配对象属性和数组值的所有摩擦。要充分掌握ES6解构的复杂性和潜力,请阅读”Getting to Grips with ES6: Destructuring“.

5) 默认和剩余参数(Default and Rest Parameters)

最后,我最想提出的ES6的两个特性是处理函数参数。几乎我们在JavaScript中创建的每个函数都接受用户数据,所以这两个特性在一个月中不止一次地派上用场。

默认参数(Default Parameters)

我们都使用过一下模式来创建具有默认值的参数:

function getarea(w,h){
  var w = w || 10
  var h = h || 15
  return w * h
}

有了ES6对默认参数的支持,显式定义的参数值的日子已经结束:

function getarea(w=10, h=15){
  return w * h
}
getarea(5) // returns 75

关于 ES6 默认参数的更多详情 在这.

剩余参数(Rest Parameters)

ES6中的 Rest Parameters 使得将函数参数转换成数组的操作变得简单。

function addit(...theNumbers){
  // get the sum of the array elements
    return theNumbers.reduce((prevnum, curnum) => prevnum + curnum, 0) 
}

addit(1,2,3,4) // returns 10

通过在命名参数前添加3个点 ...,在该位置和之后输入到函数中的参数将自动转换为数组。

没有 Rest Parameters, 我们不得不做一些复杂的操作比如 手动将参数转换为数组 :

function addit(theNumbers){
    // force arguments object into array
    var numArray = Array.prototype.slice.call(arguments) 
    return numArray.reduce((prevnum, curnum) => prevnum + curnum, 0)
}

addit(1,2,3,4) // returns 10

Rest parameters 只能应用于函数的参数的一个子集,就像下面这样,它只会将参数从第二个开始转换为数组:

function f1(date, ...lucknumbers){
    return 'The Lucky Numbers for ' + date + ' are: ' + lucknumbers.join(', ')
}

alert( f1('2017/09/29', 3, 32, 43, 52) ) // alerts "The Lucky Numbers for 2017/09/29 are 3,32,43,52"

对于 ES6 中 Rest Parameters 完整规范,看这里.

结论

你同意我所说的 ES6 特性的前五名吗?哪个是你最常用的,请在评论区和大家分享。

推荐教程:《javascript基础教程

The above is the detailed content of A look at the five most important features of JavaScript ES6. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:webhek. If there is any infringement, please contact admin@php.cn delete
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

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

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft