0% found this document useful (0 votes)
23 views

Cheat Sheet

Javascript ES6

Uploaded by

USHA GANIPISETTY
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Cheat Sheet

Javascript ES6

Uploaded by

USHA GANIPISETTY
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

QuickRef.

ME Search for cheatsheet ⌘ K Stars 6k Follow Me

ES6 cheatsheet
A quick reference cheatsheet of what's new in JavaScript for ES2015, ES2016, ES2017, ES2018
and beyond

# Getting Started
- Block-scoped - Template Strings Binary and octal literals

Let Interpolation
let bin = 0b1010010
let oct = 0o755
function fn () { const message = `Hello ${name}`
let x = 0
if (true) { Multi-line string
let x = 1 // only inside this `if`
const str = ` See: Binary and Octal Literals
}
} hello
the world
Exponential Operator
Const `

const byte = 2 **8


const a = 1

let is the new var. Constants (const) work just like Templates and multiline strings. See: template
let, but cannot be reassigned. See: Let and const strings Same as: Math.pow(2, 8)

- New library additions kind - Private class

New string methods The javascript default field is public (public), if you
class Circle extends Shape {
need to indicate private, you can use (#)
"hello".repeat(3)
Constructor
"hello". includes("ll")
"hello". startsWith("he") class Dog {
constructor (radius) { #name;
"hello".padStart(8) // "hello"
this.radius = radius constructor(name) {
"hello".padEnd(8) // "hello"
} this.#name = name;
"hello".padEnd(8, '!') // hello!!!
"\u1E9B\u0323".normalize("NFC") }
method printName() {
New Number Methods // Only private fields can be called inside
getArea () {
console.log(`Your name is ${this.#name}`)
return Math.PI *2 *this.radius
Number.EPSILON }
}
Number.isInteger(Infinity) // false }
Number.isNaN("NaN") // false
Call the superclass method
const dog = new Dog("putty")
New Math methods expand(n) {
//console.log(this.#name)
//Private identifiers are not allowed outside c
return super.expand(n) *Math.PI
Math.acosh(3) // 1.762747174039086 dog.printName()
}
Math.hypot(3, 4) // 5
Math.imul(Math.pow(2, 32) -1, Math.pow(2, 32) - Static private class
Static methods

New Array methods static createFromDiameter(diameter) {


class ClassWithPrivate {
static #privateStaticField;
return new Circle(diameter /2)
//return a real array static #privateStaticFieldWithInitializer = 42;
}
Array.from(document.querySelectorAll("*"))
//similar to new Array(...), but without the sp static #privateStaticMethod() {
Array.of(1, 2, 3) // …
}
See: New library additions Syntactic sugar for prototypes. See: classes }

# Promises
make the commitment Using Promises Using Promises in finally

new Promise((resolve, reject) => { promise promise


if (ok) { resolve(result) } .then((result) => { ··· }) .then((result) => { ··· })
else { reject(error) } .catch((error) => { ··· }) .catch((error) => { ··· })
}) .finally(() => {
/*logic independent of success/error */
})

The handler is called when the promise is fulfilled


for asynchronous programming. See: Promises or rejected

Promise function Async-await

Promise.all(···) async function run () {


Promise.race(···) const user = await getUser()
Promise.reject(···) const tweets = await getTweets(user)
Promise.resolve(···) return [user, tweets]
}

async functions are another way to use functions.


See: Async Function
# Destructuring
- Destructuring assignment Defaults Function parameters

Arrays
const scores = [22, 33] function greet({ name, greeting }) {
const [math = 50, sci = 50, arts = 50] = scores console.log(`${greeting}, ${name}!`)
const [first, last] = ['Nikola', 'Tesla']
}

Objects //Result:
//math === 22, sci === 33, arts === 50 greet({ name: 'Larry', greeting: 'Ahoy' })
let {title, author} = {
title: 'The Silkworm',
author: 'R. Galbraith'
}

Supports matching arrays and objects. See: A default value can be assigned when Destructuring of objects and arrays can also be
Destructuring destructuring an array or object done in function parameters

Defaults Reassign keys Loop

function greet({ name = 'Rauno' } = {}) { function printCoordinates({ left: x, top: y }) { for (let {title, artist} of songs) {
console.log(`Hi ${name}!`); console.log(`x: ${x}, y: ${y}`) ···
} } }

greet() // Hi Rauno! printCoordinates({ left: 25, top: 90 })


greet({ name: 'Larry' }) // Hi Larry!
This example assigns x to the value of the left key Assignment expressions also work in loops

Object Deconstruction

const { id, ...detail } = song;

Use the rest(...) operator to extract some keys


individually and the rest of the keys in the object

# Spread operator Spread


- Object Extensions - Array Expansion

with object extensions with array extension

const options = { const users = [


...defaults, ...admins,
visible: true ...editors,
} 'rstacruz'
]
No object extension
No array expansion
const options = Object.assign(
{}, defaults, const users = admins
{ visible: true }) .concat(editors)
.concat([ 'rstacruz' ])

The object spread operator allows you to build new The spread operator allows you to build new arrays
objects from other objects. See: Object Spread in the same way. See: Spread operator

# Functions
- Function parameters - Arrow function Parameter setting default value

Default parameters Arrow functions


function log(x, y = 'World') {
console.log(x, y);
function greet (name = 'Jerry') { setTimeout(() => {
}
return `Hello ${name}` ···
} })
log('Hello') // Hello World
log('Hello', 'China') // Hello China
Rest parameters with parameters
log('Hello', '') // Hello
function fn(x, ...y) { readFile('text.txt', (err, data) => {
// y is an array ...
return x * y.length })
Used in conjunction with destructuring assignment
} defaults
implicit return function foo({x, y = 5} = {}) {
Extensions console.log(x, y);
arr.map(n => n*2) }
fn(...[1, 2, 3]) //no curly braces = implicit return
//same as fn(1, 2, 3) //Same as: arr.map(function (n) { return n*2 }) foo() // undefined 5
arr.map(n => ({
result: n*2
}))
//Implicitly returning an object requires parenth name attribute

function foo() {}
Default (default), rest, spread (extension). See: Like a function, but preserves this. See: Arrow foo.name // "foo"
function parameters functions

length property

function foo(a, b){}


foo.length // 2
# Objects
Shorthand Syntax method Getters and setters

module.exports = { hello, bye } const App = { const App = {


start () { get closed () {
console.log('running') return this.status === 'closed'
same below:
} },
} set closed (value) {
module.exports = {
//Same as: App = { start: function () {···} } this.status = value ? 'closed' : 'open'
hello: hello, bye: bye
}
}
}

See: Object Literals Enhanced See: Object Literals Enhanced See: Object Literals Enhanced

Computed property name Extract value

let event = 'click' const fatherJS = { age: 57, name: "Zhang San" }
let handlers = { Object.values(fatherJS)
[`on${event}`]: true //[57, "Zhang San"]
} Object.entries(fatherJS)
//Same as: handlers = { 'onclick': true } //[["age", 57], ["name", "Zhang San"]]

See: Object Literals Enhanced

# Modules module
Imports import Exports export as keyword renaming

import 'helpers' export default function () { ··· } import {


//aka: require('···') //aka: module.exports.default = ··· lastName as surname // import rename
} from './profile.js';

import Express from 'express' export function mymethod () { ··· }


function v1() { ... }
//aka: const Express = require('···').default | //aka: module.exports.mymethod = ···
function v2() { ... }

import { indent } from 'helpers' export const pi = 3.14159 export { v1 as default };


//aka: const indent = require('···').indent //aka: module.exports.pi = ··· //Equivalent to export default v1;

export {
import *as Helpers from 'helpers' const firstName = 'Michael';
v1 as streamV1, // export rename
//aka: const Helpers = require('···') const lastName = 'Jackson';
v2 as streamV2, // export rename
const year = 1958;
v2 as streamLatestVersion // export rename
export { firstName, lastName, year };
import { indentSpaces as indent } from 'helpers };
//aka: const indent = require('···').indentSpac
export *from "lib/math";

export is the new module.exports. See: Module


import is the new require(). See: Module imports exports

Dynamically load modules import() allows module paths to be dynamically generated - import.meta

button.addEventListener('click', event => { const main = document.querySelector('main') ES2020 Added a meta property import.meta to the
import('./dialogBox.js') import command, which returns the meta
.then(dialogBox => { import(`./modules/${someVariable}.js`) information of the current module
dialogBox. open(); .then(module => {
}) module.loadPageInto(main); new URL('data.txt', import.meta.url)
.catch(error => { })
/*Error handling */ .catch(err => {
}) main.textContent = err.message;
In the Node.js environment, import.meta.url
}); });
always returns a local path, that is, a string of the
file:URL protocol, such as file:///
ES2020 Proposal introduce import() function home/user/foo.js

- Import Assertions

static import

import json from "./package.json" assert {type: "json"}


//Import all objects in the json file

Dynamic Import

const json =
await import("./package.json", { assert: { type: "json" } })

# Generators
Generator function For..of + iterator Relationship with Iterator interface

function*idMaker () { let fibonacci = { var gen = {};


let id = 0 [Symbol.iterator]() { gen[Symbol.iterator] = function*() {
while (true) { yield id++ } let pre = 0, cur = 1; yield 1;
} return { yield 2;
next() { yield 3;
[pre, cur] = [cur, pre + cur]; };
let gen = idMaker()
return { done: false, value: cur }
gen.next().value // → 0
} [...gen] // => [1, 2, 3]
gen.next().value // → 1
}
gen.next().value // → 2
} The Generator function is assigned to the
} Symbol.iterator property, so that the gen object
has the Iterator interface, which can be traversed
for (var n of fibonacci) { by the ... operator
it's complicated. See: Generators
// truncate sequence at 1000
if (n > 1000) break;
Symbol.iterator property console.log(n);
}
function*gen() { /*some code */}
var g = gen();

g[Symbol.iterator]() === g // true

gen is a Generator function, calling it will generate


a traverser object g. Its Symbol.iterator property,
which is also an iterator object generation For iterating over generators and arrays. See:
function, returns itself after execution For..of iteration

# see also
Learn ES2015(babeljs.io)
ECMAScript 6 Features Overview (github.com)

Related Cheatsheet Recent Cheatsheet


QuickRef.ME
Express Cheatsheet JSON Cheatsheet Remote Work Revolution Homebrew Cheatsheet
Share quick reference and cheat sheet for
Quick Reference Quick Reference Quick Reference Quick Reference
developers.

中文版 #Notes
Kubernetes Cheatsheet TOML Cheatsheet PyTorch Cheatsheet Taskset Cheatsheet
Quick Reference Quick Reference Quick Reference Quick Reference

© 2023 QuickRef.ME, All rights reserved.

You might also like