Block scoping
Let
function fn () {
let x = 0
if (true) {
let x = 1 // only inside this `if`
}
}
Copy the code
Const
const a = 1
Copy the code
Let is the new var. Constants Work just like let, but can’t be reassigned. See: let and const
Backtick strings
Interpolation
var message = `Hello ${name}`
Copy the code
Multiline strings
var str = `
hello
world
`
Copy the code
Templates and multiline strings. See: Template strings
Binary and octal literals
let bin = 0b1010010
let oct = 0o755
Copy the code
See: Binary and octal literals
New methods
New string methods
"hello".repeat(3)
"hello".includes("ll")
"\u1E9B\u0323".normalize("NFC")
Copy the code
See: New methods
Classes
class Circle extends Shape {
Copy the code
Constructor
constructor (radius) {
this.radius = radius
}
Copy the code
Methods
getArea () {
return Math.PI * 2 * this.radius
}
Copy the code
Calling superclass methods
expand (n) {
return super.expand(n) * Math.PI
}
Copy the code
Static methods
static createFromDiameter(diameter) {
return new Circle(diameter / 2)
}
}
Copy the code
Syntactic sugar for prototypes. See: Classes
Exponent operator
const byte = 2 ** 8
// Same as: Math.pow(2, 8)
Copy the code
Promises
Making promises
new Promise((resolve, reject) => {
if (ok) { resolve(result) }
else { reject(error) }
})
Copy the code
For asynchronous programming. See: Promises
Using promises
Promise. Then ((result) = > {...}). The catch ((error) = > {...})Copy the code
Promise functions
Promise. All (...) Promise. Race (...) Promise. Reject (...) Promise. Resolve (...)Copy the code
Async-await
async function run () {
const user = await getUser()
const tweets = await getTweets(user)
return [user, tweets]
}
Copy the code
async
functions are another way of using functions.
See: async function
Destructuring
Destructuring assignment
Arrays
var [first, last] = ['Nikola', 'Tesla']
Copy the code
Objects
let {title, author} = {
title: 'The Silkworm',
author: 'R. Galbraith'
}
Copy the code
Supports for matching arrays and objects. See: Destructuring
Default values
var scores = [22, 33]
var [math = 50, sci = 50, arts = 50] = scores
Copy the code
// Result:
// math === 22, sci === 33, arts === 50
Copy the code
Default values can be assigned while destructuring arrays or objects.
Function arguments
function greet({ name, greeting }) {
console.log(`${greeting}, ${name}!`)
}
Copy the code
greet({ name: 'Larry', greeting: 'Ahoy' })
Copy the code
Destructuring of objects and arrays can be also be done in function arguments.
Reassigning keys
function printCoordinates({ left: x, top: y }) {
console.log(`x: ${x}, y: ${y}`)
}
Copy the code
printCoordinates({ left: 25, top: 90 })
Copy the code
This example assigns x
to the value of the left
key.
Loops
For (let {title, artist} in songs) {···}Copy the code
The assignment expressions work in loops, too.
Spread
Object spread
with Object spread
const options = { ... defaults, visible: true }Copy the code
without Object spread
const options = Object.assign(
{}, defaults,
{ visible: true })
Copy the code
The Object spread operator lets you build new objects from other objects.
See: Object spread
Array spread
with Array spread
const users = [
...admins,
...editors,
'rstacruz'
]
Copy the code
without Array spread
const users = admins
.concat(editors)
.concat([ 'rstacruz' ])
Copy the code
The spread operator lets you build new arrays in the same way.
See: Spread operator
Functions
Function arguments
Default arguments
function greet (name = 'Jerry') {
return `Hello ${name}`
}
Copy the code
Rest arguments
function fn(x, ... y) { // y is an Array return x * y.length }Copy the code
Spread
fn(... [1, 2, 3]) // same as fn(1, 2, 3)Copy the code
Default, rest, spread. See: Function arguments
Fat arrows
Fat arrows
SetTimeout (() => {···})Copy the code
With arguments
readFile('text.txt', (err, data) => {
...
})
Copy the code
Implicit return
numbers.map(n => n * 2)
// No curly braces = implicit return
// Same as: numbers.map(function (n) { return n * 2 })
Copy the code
Like functions but with this
preserved. See: Fat arrows
Objects
Shorthand syntax
module.exports = { hello, bye }
// Same as: module.exports = { hello: hello, bye: bye }
Copy the code
See: Object literal enhancements
Methods
Const App = {start () {console.log('running')}} // Same as: App = {start: function () {···}}Copy the code
See: Object literal enhancements
Getters and setters
const App = {
get closed () {
return this.status === 'closed'
},
set closed (value) {
this.status = value ? 'closed' : 'open'
}
}
Copy the code
See: Object literal enhancements
Computed property names
let event = 'click'
let handlers = {
[`on${event}`]: true
}
// Same as: handlers = { 'onclick': true }
Copy the code
See: Object literal enhancements
Modules
Imports
Import 'helpers' // aka: require('···')Copy the code
The import Express the from 'Express' / / aka: Express = the require ('... '). The default | | the require ('... ')Copy the code
Import {indent} from 'helpers' // aka: indent = require('···')Copy the code
Import * as Helpers from 'Helpers' // aka: Helpers = require('... ')Copy the code
Import {indentSpaces as indent} from 'helpers' // aka: indent = require('···')Copy the code
import
is the new require()
. See: Module imports
Exports
Export default function () {···} // aka: module.exports. Default = ···Copy the code
Export function myMethod () {···} // aka: module.exports.mymethod = ···Copy the code
Export const PI = 3.14159 // aka: module.exports. PI = ···Copy the code
export
is the new module.exports
. See: Module exports
Generators
Generators
function* idMaker () {
var id = 0
while (true) { yield id++ }
}
Copy the code
Var gen = idMaker() gen.next().value // → 0 gen.next().value // → 1 gen.next().value // → 2Copy the code
It ‘s complicated. See: Generators
For.. of iteration
For (let I of iterable) {···}Copy the code
For iterating through generators and arrays. See: For.. of iteration