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 Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

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.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

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

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

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.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

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: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

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.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

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

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

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.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

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.

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor