View on GitHub

Note: A commonly accepted practice is to use const except in cases of loops and reassignment. However, in this resource I'll be using let in place of var for all ES6 examples.

  • Variable: x
  • Object: obj
  • Array: arr
  • Function: func
  • Parameter, method: a, b, c
  • String: str

Table of contents

  • Variable declaration
  • Constant declaration
  • Arrow function syntax
  • Template literals
  • Implicit returns
  • Key/property shorthand
  • Method definition shorthand
  • Destructuring (object matching)
  • Array iteration (looping)
  • Default parameters
  • Spread syntax
  • Classes/constructor functions
  • Inheritance
  • Modules - export/import
  • Promises/callbacks

Variables and constant feature comparison

Understanding Variables, Scope, and Hoisting in JavaScript

Keyword Scope Hoisting Can Be Reassigned Can Be Redeclared
var Function scope Yes Yes Yes
let Block scope No Yes No
const Block scope No No No

Variable declaration

ES6 introduced the let keyword, which allows for block-scoped variables which cannot be hoisted or redeclared.

MDN Reference: let

Constant declaration

ES6 introduced the const keyword, which cannot be redeclared or reassigned, but is not immutable.

MDN Reference: const

Arrow functions

The arrow function expression syntax is a shorter way of creating a function expression. Arrow functions do not have their own this, do not have prototypes, cannot be used for constructors, and should not be used as object methods.

# ES5

function func(a, b, c) {} // function declaration
var func = function(a, b, c) {} // function expression #ES6 let func = a => {} // parentheses optional with one parameter
let func = (a, b, c) => {} // parentheses required with multiple parameters

  MDN Reference: Arrow functions

Template literals(模板文字)

Concatenation/string interpolation

Expressions can be embedded in template literal strings.

# ES5

var str = 'Release date: ' + date

# ES6

let str = `Release Date: ${date}`

  MDN Reference: Expression interpolation

Multi-line strings

Using template literal syntax, a JavaScript string can span multiple lines without the need for concatenation.

#ES5

var str = 'This text ' + 'is on ' + 'multiple lines'

# ES6

let str = `This text
is on
multiple lines`

  

Note: Whitespace is preserved in multi-line template literals. See Removing leading whitespace in ES6 template strings.

Implicit returns

The return keyword is implied and can be omitted if using arrow functions without a block body.

# ES5

function func(a, b, c) {
return a + b + c
} # ES6 let func = (a, b, c) => a + b + c // curly brackets must be omitted

 MDN Reference: Function body

Key/property shorthand

ES6 introduces a shorter notation for assigning properties to variables of the same name.

# ES5

var obj = {
a: a,
b: b,
} # ES6 let obj = {
a,
b,
}

  MDN Reference: Property definitions

Method definition shorthand

The function keyword can be omitted when assigning methods on an object.

# ES5

var obj = {
a: function(c, d) {},
b: function(e, f) {},
} # ES6 let obj = {
a(c, d) {},
b(e, f) {},
}
obj.a() // call method a

  MDN Reference: Method definitions

Destructuring (object matching)

Use curly brackets to assign properties of an object to their own variable.

var obj = { a: 1, b: 2, c: 3 }

# ES5

var a = obj.a
var b = obj.b
var c = obj.c # ES6 let { a, b, c } = obj

  MDN Reference: Object initializer

Array iteration (looping)

A more concise syntax has been introduced for iteration through arrays and other iterable objects.

var arr = ['a', 'b', 'c']

# ES5

for (var i = 0; i < arr.length; i++) {
console.log(arr[i])
} # ES6 for (let i of arr) {
console.log(i)
}

  MDN Reference: for...of

Default parameters

Functions can be initialized with default parameters, which will be used only if an argument is not invoked through the function.

# ES5

var func = function(a, b) {
b = b === undefined ? 2 : b
return a + b
} # ES6 let func = (a, b = 2) => {
return a + b
} func(10) // returns 12
func(10, 5) // returns 15

  MDN Reference: Default paramters

Spread syntax

Spread syntax can be used to expand an array.

# ES6

let arr1 = [1, 2, 3]
let arr2 = ['a', 'b', 'c']
let arr3 = [...arr1, ...arr2] console.log(arr3) // [1, 2, 3, "a", "b", "c"]

Spread syntax can be used for function arguments.

# ES6

let arr1 = [1, 2, 3]
let func = (a, b, c) => a + b + c console.log(func(...arr1)) // 6

  MDN Reference: Spread syntax

Classes/constructor functions

ES6 introducess the class syntax on top of the prototype-based constructor function.

# ES5

function Func(a, b) {
this.a = a
this.b = b
} Func.prototype.getSum = function() {
return this.a + this.b
} var x = new Func(3, 4) # ES6 class Func {
constructor(a, b) {
this.a = a
this.b = b
} getSum() {
return this.a + this.b
}
} let x = new Func(3, 4) x.getSum() // returns 7

  MDN Reference: Classes

Inheritance

The extends keyword creates a subclass.

# ES5

function Inheritance(a, b, c) {
Func.call(this, a, b) this.c = c
} Inheritance.prototype = Object.create(Func.prototype)
Inheritance.prototype.getProduct = function() {
return this.a * this.b * this.c
} var y = new Inheritance(3, 4, 5) # ES6 class Inheritance extends Func {
constructor(a, b, c) {
super(a, b) this.c = c
} getProduct() {
return this.a * this.b * this.c
}
} let y = new Inheritance(3, 4, 5) y.getProduct() // 60

  MDN Reference: Subclassing with extends

Modules - export/import

Modules can be created to export and import code between files.

# index.html

<script src="export.js"></script>
<script type="module" src="import.js"></script> # export.js let func = a => a + a
let obj = {}
let x = 0 export { func, obj, x } # import.js import { func, obj, x } from './export.js' console.log(func(3), obj, x)

  

Promises/Callbacks

Promises represent the completion of an asynchronous function. They can be used as an alternative to chaining functions.

# ES5 callback

function doSecond() {
console.log('Do second.')
} function doFirst(callback) {
setTimeout(function() {
console.log('Do first.') callback()
}, 500)
} doFirst(doSecond) # ES6 Promise let doSecond = () => {
console.log('Do second.')
} let doFirst = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Do first.') resolve()
}, 500)
}) doFirst.then(doSecond)

  

An example below using XMLHttpRequest, for demonstrative purposes only (Fetch API would be the proper modern API to use).

# ES5 callback

function makeRequest(method, url, callback) {
var request = new XMLHttpRequest() request.open(method, url)
request.onload = function() {
callback(null, request.response)
}
request.onerror = function() {
callback(request.response)
}
request.send()
} makeRequest('GET', 'https://url.json', function(err, data) {
if (err) {
throw new Error(err)
} else {
console.log(data)
}
}) # ES6 Promise function makeRequest(method, url) {
return new Promise((resolve, reject) => {
let request = new XMLHttpRequest() request.open(method, url)
request.onload = resolve
request.onerror = reject
request.send()
})
} makeRequest('GET', 'https://url.json')
.then(event => {
console.log(event.target.response)
})
.catch(err => {
throw new Error(err)
})

  

If you found this useful, please share!

 

ES6 Syntax and Feature Overview的更多相关文章

  1. Photon——Feature Overview 功能概述

    Photon——Feature Overview 功能概述   Feature Overview 功能概述        Photon is a real-time socket server and ...

  2. Javescript——变量声明的区别

    原文链接:ES6 Syntax and Feature Overview View on GitHub Keyword Scope Hoisting Can Be Reassigned Can Be ...

  3. Sublime Es6教程1-环境搭建

    因为现在网上的教程都不靠谱,于是决定自己跳坑自己写,分为三块来玩: 一.环境搭建 二.语法讲解 三.项目实战 很多时候,你想搞一个东西,却因为环境没有搭建好,而不能很开森的探索未知的世界,多年的编程经 ...

  4. ES6语法糖集锦

    sublime3安装Es6插件 javascriptNext,然后安装即可 Java​Script​Next - ES6 Syntax()高亮插件 -------------------------- ...

  5. vscode插件-JavaScript(ES6) Code Snippets 缩写代表含义

    Import and export Trigger Content imp→ imports entire module import fs from 'fs'; imn→ imports entir ...

  6. Fundamental ES6 Part-I

    Exercise-01 with Solution Write a JavaScript program to compare two objects to determine if the firs ...

  7. JavaScript资源大全中文版(Awesome最新版)

    Awesome系列的JavaScript资源整理.awesome-javascript是sorrycc发起维护的 JS 资源列表,内容包括:包管理器.加载器.测试框架.运行器.QA.MVC框架和库.模 ...

  8. dfsdf

    This project was bootstrapped with Create React App. Below you will find some information on how to ...

  9. BETTER SUPPORT FOR FUNCTIONAL PROGRAMMING IN ANGULAR 2

    In this blog post I will talk about the changes coming in Angular 2 that will improve its support fo ...

随机推荐

  1. 从Retrofit的源码来看 HTTP

    关于Retrofit是啥,这里就不多解释了,还是先来瞅下官网: 而这次主要是了解它的底层动作机制,而在了解底层之前先来回顾一下官网的整体使用步骤: 咱们也以官网的这个例子为例,先从简单的使用开始逐步深 ...

  2. 安装Genymotion模拟器(第三方)

    优势: 启动速度更快 注册账户,下载可用的系统镜像,就可以使用.     官方网站: https://www.genymotion.com/account/login/ 选择的版本是带VirtualB ...

  3. 搭建jenkins+python+selenium+robot framework环境

    1.安装jenkins 具体参考:https://www.cnblogs.com/dydxw/p/10538103.html 2.下载插件 我是为了方便,把有关python.selenium.robo ...

  4. qsort中的函数指针,及函数解释

    函数指针有何用 函数指针的应用场景比较多,以库函数qsort排序函数为例,它的原型如下: void qsort(void *base,size_t nmemb,size_t size , int(*c ...

  5. Educational Codeforces Round 75 (Rated for Div. 2) A. Broken Keyboard

    链接: https://codeforces.com/contest/1251/problem/A 题意: Recently Polycarp noticed that some of the but ...

  6. [go] 循环与函数

    练习:循环与函数 为了练习函数与循环,我们来实现一个平方根函数:用牛顿法实现平方根函数. 计算机通常使用循环来计算 x 的平方根.从某个猜测的值 z 开始,我们可以根据 z² 与 x 的近似度来调整 ...

  7. Spring第四天

    顾问包装通知 通知(advice)是Spring中的一种比较简单的切面,只能将切面织入到目标类的所有方法中,而无法对指定方法进行增强 顾问(advisor)是Spring提供的另外一种切面,可以织入到 ...

  8. VsCode安装Go的相关插件

    今天在学习Go的时候,安装Go的相关插件,显示安装不上,但是右下角也一直会提示让你安装,当然你可以设置成忽略,为了开发效率,我选择了安装.然后出现了问题,一直Failed.在网上看到了很多的文章,不是 ...

  9. TensorFlow(十四):谷歌图像识别网络inception-v3下载与查看结构

    上代码: import tensorflow as tf import os import tarfile import requests #inception模型下载地址 inception_pre ...

  10. Ubuntu上配置vtk开发环境——基于visual studio code 与 gcc

    环境说明 vtk版本7.1.1 visual studio 1.16.1 Ubuntu 16.04 + 自带的gcc 编译过程与windows下类似还好,运行自己的代码开始面对cmake与make的各 ...