神刀安全网

Toptal's Quick And Practical JavaScript Cheat Sheet: ES6 And Beyond

ECMAScript 6(ES6) is the latest standard specification of JavaScript , the programming language of the Web. Since HTML5 and the birth of Node.js , the runtime that allows us to runJavaScript on the server or desktop, JavaScript has gained a unique momentum. There is a growing adoption rate among enterprises, embracing it into production, and thus its newest features were greatly awaited.

We created this cheat sheet as a list of ES6 features we use everyday. Trying to be comprehensive but concise at the same time, new API methods are left apart. For those who need them, make a quick search by yourself or try to explore the MDN documentation to catch the latest experimental APIs. However, some the most bleeding edge characteristics like async and await from the next specification draft (ES7) are included. This is because of most of us developers are going to use a transpiler like Babel anyway to get advantage of the newest JavaScript.

You can test out some of the mentioned tips by running the node REPL with this command:

node --use-strict $(node --v8-options | grep harm | awk '{print $1}' | xargs) #ES6 

Or, use directly a babel-node to get the most of Javascript in your console.

Related: A Practical CSS Cheat Sheet by Toptal Developers

Toptal's Quick And Practical JavaScript Cheat Sheet: ES6 And Beyond

Click Here To Download JavaScript ES6 Cheat Sheet

JavaScript (ES6 and Beyond) Cheat Sheet

Constants

let vs var

> const EULER = 2.7182818284

> EULER = 13

> EULER

> 2.7182818284

> var average = 5

> var average = (average + 1) / 2

> average

> 3

> let value = ‘hello world’

> let value = ‘what is new’

// -> throws TypeError: Identifier ‘value’ has already been declared

Warning! If array or object, the reference is kept constant . If the constant is a reference to an object, you can still modify the content, but never change the variable.

> const CONSTANTS = []

> CONSTANTS.push(EULER)

> CONSTANTS

> [ 2.7182818284 ]

> CONSTANTS = { ‘euler’: 2.7182818284 }

> CONSTANTS

> [ 2.7182818284 ]

Be aware of Temporal Dead Zones :

> console.log(val)  // -> ‘undefined’

> var val = 3

> console.log(val)

 // -> 3

Because it’s equivalent to:

Binary, Octal and Hex Notation

> var val
> console.log(val)
> val = 3
> console.log(val)

> 0b1001011101 // 605

> 0o6745 // 3557

> 0x2f50a

// 193802

Variables declared with "let/const" do not get hoisted:

New Types

> console.log(val)

// -> Throws ReferenceError

> let val = 3

> console.log(val)

// -> 3

Symbols, Maps, WeakMaps and Sets

Arrow Function

New Scoped Functions

> setTimeout(() => {

…  console.log(‘delayed’)

… }, 1000)

> {

… let cue = ‘Luke, I am your father’

  console.log(cue)

… }

> ‘Luke, I am your father’

Equivalent with Anonymous Function

Equivalent with Immediately Invoked Function Expressions (IIFE)

> setTimeout(function () {

…   console.log(‘delayed’)

… }.bind(this), 1000)

>

(function () {

… var cue = ‘Luke, I am your father’

… console.log(cue) // ‘Luke, I am –

… }())

> console.log(cue)

// Reference Error

Object Notation Novelties

String Interpolation, Thanks to Template Literals

// Computed properties

> let key = new Date().getTime()

> let obj = {  [key]: “value” }

> obj

> { ‘1459958882881’: ‘value’ }

// Object literals
balloon = { color, size };

// Same as

balloon = {

color: color,

size: size

}
// Better method notations
obj = {
foo (a, b) { … },
bar (x, y) { … }
}

> const name = ‘Tiger’

> const age = 13

console.log (`My cat is named ${name} and is ${age} years old.`)

> My cat is named Tiger and is 13 years old.

// We can preserve newlines…

let

text = ( `cat

dog

nickelodeon`

)

Default Params

> function howAreYou (answer = ‘ok’) {      

console.log(answer) // probably  ‘ok’

}

Promises

Classes, Inheritance, Setters, Getters

new Promise((resolve, reject) => {

request.get(url, (error, response,  

body) => {

if (body) {

resolve(JSON.parse(body));

} else {

resolve({});

}

})

}).then(() => { … })

.catch((err) => throw err)

// Parallelize tasks

Promise.all([

promise1, promise2, promise3

]).then(() => {

// all tasks are finished

})

class Rectangle extends Shape {

constructor (id, x, y, w, h) {

super(id, x, y)

this.width = w

this.height = h

}

// Getter and setter

set width (w) { this._width = w }

get width () { return this._width }

}

class Circle extends Shape {

constructor (id, x, y, radius) {

super(id, x, y)

this.radius = radius

}

do_a (x) {

let a = 12;

super.do_a(x + a);

}

static do_b() { … }

}

Circle.do_b()

Destructuring Arrays

Destructuring Objects

> let [one, two, c, d] = [1, 2, 3, 4];

> 1
> b

> 2

> let luke = {  occupation: ‘jedi’,

father: ‘anakin’ }

> let {occupation, father} = luke

> jedi anakin

Spread Operator

…Go Destructuring Like a Boss

// Turn arrays into comma separated

// values and more

> function logger (…args) {

console.log(‘%s arguments’,

args.length)

args.forEach(console.log)

// arg[0], arg[1], arg[2]

}

> const [ cat, dog, …fish ] = [

‘schroedinger’,  ‘Laika’, ‘Nemo’, ‘Dori’]

> fish // -> [‘Nemo’, ‘Dori’]

Or Do a Better Push

…And Destructuring in the Future    ⚠ ES7

> let arr = [1, 2, 3]

> […arr, 4, 5, 6]

> [1, 2, 3, 4, 5, 6]

{a, b, …rest} = {a:1, b:2, c:3, d:4}

Async   ⚠ ES7

Await   ⚠ ES7

async function schrodinger  () {

return new Promise((resolve, reject)

=> {

const result = Math.random > 0.5

setTimeout(() => {

return result ? resolve(‘alive’)

: reject(‘dead’)

})

})

}

try {

console.log(await schrodinger())

// -> ‘alive’

} catch (err) {

console.log(err)

// -> ‘dead’

}

Export   ⚠ ES7

Importing   ⚠ ES7

export function sumTwo (a, b) {
return a + b;
}
export const EULER = 2.7182818284
let stuff = { sumTwo, EULER }
export { stuff as default }

import React from ‘react’

import { EULER } from ‘./myexports’

import * as stuff from ‘./myexports’

// equivalent to

import stuff from ‘./myexports’

// { sumTwo, EULER }

Generators

They  return a objects that implement an iteration protocol. i.e. it has a next() method that returns { value: < some value>, done: <true or false> } .

function* incRand (max) { // Asterisk defines this as a generator

while (true) {

// when next(<something>) is called

// and assign <something> to x

let x = yield Math.floor(Math.random() * max + 1);

max += x;

}

}

> var rng = incRand(2) // Returns a generator object

> rng.next() // { value: <between 1 and 2>, done: false }

> rng.next(3) // as above, but between 1 and 5

> rng.next() // NaN since 5 + undefined results in NaN

> rng.throw(new Error(‘Unrecoverable generator state.’))

// Will be thrown from yield

About the author

Jesus Dario Rivera, Germany

member since September 18, 2015

JavaScript CSS React.js

Jesus is a co-founder of netbeast.co. Recently graduated with a Bachelor’s in Engineering at the University of Sevilla, he has 2 years of experience as full-stack developer as well as a year of experience as CTO, managing a team of engineers and making executive decisions. [click to continue…]

Hiring? Meet the Top 10 Freelance JavaScript Developers for Hire in May 2016

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Toptal's Quick And Practical JavaScript Cheat Sheet: ES6 And Beyond

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址