ES6 Syntax and Feature Overview
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.
Constant declaration
ES6 introduced the const keyword, which cannot be redeclared or reassigned, but is not immutable.
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
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)
}
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
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
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的更多相关文章
- Photon——Feature Overview 功能概述
Photon——Feature Overview 功能概述 Feature Overview 功能概述 Photon is a real-time socket server and ...
- Javescript——变量声明的区别
原文链接:ES6 Syntax and Feature Overview View on GitHub Keyword Scope Hoisting Can Be Reassigned Can Be ...
- Sublime Es6教程1-环境搭建
因为现在网上的教程都不靠谱,于是决定自己跳坑自己写,分为三块来玩: 一.环境搭建 二.语法讲解 三.项目实战 很多时候,你想搞一个东西,却因为环境没有搭建好,而不能很开森的探索未知的世界,多年的编程经 ...
- ES6语法糖集锦
sublime3安装Es6插件 javascriptNext,然后安装即可 JavaScriptNext - ES6 Syntax()高亮插件 -------------------------- ...
- vscode插件-JavaScript(ES6) Code Snippets 缩写代表含义
Import and export Trigger Content imp→ imports entire module import fs from 'fs'; imn→ imports entir ...
- Fundamental ES6 Part-I
Exercise-01 with Solution Write a JavaScript program to compare two objects to determine if the firs ...
- JavaScript资源大全中文版(Awesome最新版)
Awesome系列的JavaScript资源整理.awesome-javascript是sorrycc发起维护的 JS 资源列表,内容包括:包管理器.加载器.测试框架.运行器.QA.MVC框架和库.模 ...
- dfsdf
This project was bootstrapped with Create React App. Below you will find some information on how to ...
- 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 ...
随机推荐
- PAT基础级-钻石段位样卷2-7-5 福到了 (15 分)
“福”字倒着贴,寓意“福到”.不论到底算不算民俗,本题且请你编写程序,把各种汉字倒过来输出.这里要处理的每个汉字是由一个 N × N 的网格组成的,网格中的元素或者为字符 @ 或者为空格.而倒过来的汉 ...
- IIS 自动化发布工具实现【一】
[持续更新中啦] 过去一年,有在尝试做.net 这块的开发运维工作.基于现在的开发场景,写了一套差异发布工具.后面用python重写了一套,现学现卖. 主要功能: 差异打包.自动发布.自动回滚 实现架 ...
- python中IO多路复用、协程
一.IO多路复用 IO多路复用:检测多个socket是否已经发生变化(是否已经连接成功/是否已经获取数据)(可读/可写) import socket def get_data(key): client ...
- IntelliJ IDEA lombok插件的安装和使用
IntelliJ IDEA是一款非常优秀的集成开发工具,功能强大,而且插件众多.lombok是开源的代码生成库,是一款非常实用的小工具,我们在编辑实体类时可以通过lombok注解减少getter.se ...
- Vue、webpack中默认的config.js、index.js 配置详情
在vue.js 框架搭建好后,其vue-cli 自动构建的目录里面相关环境变量及其基本变量配置,如下代码所示: module.exports = { build: { index: path.reso ...
- 命令检测站点是否使用CDN加速
在CMD 输入 nslookup 域名 例如:nslookup www.baidu.com有CDN的示例Server: cache3-gzAddress: 211.98.4.1Non ...
- PHP启动php-fpm成功,但php-cgi进程查找不到 502 getaway
一般情况大家刚把lnmp环境安装好之后,把nginx中 fastcgi_pass unix:/tmp/php-cgi.sock项修改成 fastcgi_pass 127.0.0.1:9000之后,网页 ...
- Java原子类--AtomicLong
转载请注明出处:http://www.cnblogs.com/skywang12345/p/3514593.html AtomicLong介绍和函数列表 AtomicLong是作用是对长整形进行原子操 ...
- 记录从裸机到TensorFlow GPU版运行 的配置过程
实验室原来有一台装Ubuntu Server系统的服务器,安装有tensorflow,在使用过程中经常出现断网.死机.自动关机等毛病,忍无可忍,决定重装系统 配置如下:Dell工作站,Xeon-E5 ...
- List<Map<String, Obejct>>遍历
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map&l ...