Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
E

es6-cheatsheet

> 编程语言
Open source

ES2015 [ES6] cheatsheet containing tips, tricks, best practices and code snippets

13.3K stars0 likes2 views
WebsiteGitHub

About

ES2015 [ES6] cheatsheet containing tips, tricks, best practices and code snippets

es6-cheatsheet

A cheatsheet containing ES2015 [ES6] tips, tricks, best practices and code snippet examples for your day to day workflow. Contributions are welcome!

Table of Contents

  • var versus let / const
  • Replacing IIFEs with Blocks
  • Arrow Functions
  • Strings
  • Destructuring
  • Modules
  • Parameters
  • Classes
  • Symbols
  • Maps
  • WeakMaps
  • Promises
  • Generators
  • Async Await
  • Getter/Setter functions
  • License

var versus let / const

Besides var, we now have access to two new identifiers for storing values —let and const. Unlike var, let and const statements are not hoisted to the top of their enclosing scope.

An example of using var:

javascript
var snack = 'Meow Mix';

function getFood(food) {
    if (food) {
        var snack = 'Friskies';
        return snack;
    }
    return snack;
}

getFood(false); // undefined

However, observe what happens when we replace var using let:

javascript
let snack = 'Meow Mix';

function getFood(food) {
    if (food) {
        let snack = 'Friskies';
        return snack;
    }
    return snack;
}

getFood(false); // 'Meow Mix'

This change in behavior highlights that we need to be careful when refactoring legacy code which uses var. Blindly replacing instances of var with let may lead to unexpected behavior.

Note: let and const are block scoped. Therefore, referencing block-scoped identifiers before they are defined will produce a ReferenceError.

javascript
console.log(x); // ReferenceError: x is not defined

let x = 'hi';

Best Practice: Leave var declarations inside of legacy code to denote that it needs to be carefully refactored. When working on a new codebase, use let for variables that will change their value over time, and const for variables which cannot be reassigned.

(back to table of contents)

Replacing IIFEs with Blocks

A common use of Immediately Invoked Function Expressions is to enclose values within its scope. In ES6, we now have the ability to create block-based scopes and therefore are not limited purely to function-based scope.

javascript
(function () {
    var food = 'Meow Mix';
}());

console.log(food); // Reference Error

Using ES6 Blocks:

javascript
{
    let food = 'Meow Mix';
};

console.log(food); // Reference Error

(back to table of contents)

Arrow Functions

Often times we have nested functions in which we would like to preserve the context of this from its lexical scope. An example is shown below:

javascript
function Person(name) {
    this.name = name;
}

Person.prototype.prefixName = function (arr) {
    return arr.map(function (character) {
        return this.name + character; // Cannot read property 'name' of undefined
    });
};

One common solution to this problem is to store the context of this using a variable:

javascript
function Person(name) {
    this.name = name;
}

Person.prototype.prefixName = function (arr) {
    var that = this; // Store the context of this
    return arr.map(function (character) {
        return that.name + character;
    });
};

We can also pass in the proper context of this:

javascript
function Person(name) {
    this.name = name;
}

Person.prototype.prefixName = function (arr) {
    return arr.map(function (character) {
        return this.name + character;
    }, this);
};

As well as bind the context:

javascript
function Person(name) {
    this.name = name;
}

Person.prototype.prefixName = function (arr) {
    return arr.map(function (character) {
        return this.name + character;
    }.bind(this));
};

Using Arrow Functions, the lexical value of this isn't shadowed and we can re-write the above as shown:

javascript
function Person(name) {
    this.name = name;
}

Person.prototype.prefixName = function (arr) {
    return arr.map(character => this.name + character);
};

Best Practice: Use Arrow Functions whenever you need to preserve the lexical value of this.

Arrow Functions are also more concise when used in function expressions which simply return a value:

javascript
var squares = arr.map(function (x) { return x * x }); // Function Expression
javascript
const arr = [1, 2, 3, 4, 5];
const squares = arr.map(x => x * x); // Arrow Function for terser implementation

Best Practice: Use Arrow Functions in place of function expressions when possible.

(back to table of contents)

Strings

With ES6, the standard library has grown immensely. Along with these changes are new methods which can be used on strings, such as .includes() and .repeat().

.includes( )

javascript
var string = 'food';
var substring = 'foo';

console.log(string.indexOf(substring) > -1);

Instead of checking for a return value > -1 to denote string containment, we can simply use .includes() which will return a boolean:

javascript
const string = 'food';
const substring = 'foo';

console.log(string.includes(substring)); // true

.repeat( )

javascript
function repeat(string, count) {
    var strings = [];
    while(strings.length < count) {
        strings.push(string);
    }
    return strings.join('');
}

In ES6, we now have access to a terser implementation:

javascript
// String.repeat(numberOfRepetitions)
'meow'.repeat(3); // 'meowmeowmeow'

Template Literals

Using Template Literals, we can now construct strings that have special characters in them without needing to escape them explicitly.

javascript
var text = "This string contains \"double quotes\" which are escaped.";
javascript
let text = `This string contains "double quotes" which don't need to be escaped anymore.`;

Template Literals also support interpolation, which makes the task of concatenating strings and values:

javascript
var name = 'Tiger';
var age = 13;

console.log('My cat is named ' + name + ' and is ' + age + ' years old.');

Much simpler:

javascript
const name = 'Tiger';
const age = 13;

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

In ES5, we handled new lines as follows:

javascript
var text = (
    'cat\n' +
    'dog\n' +
    'nickelodeon'
);

Or:

javascript
var text = [
    'cat',
    'dog',
    'nickelodeon'
].join('\n');

Template Literals will preserve new lines for us without having to explicitly place them in:

javascript
let text = ( `cat
dog
nickelodeon`
);

Template Literals can accept expressions, as well:

javascript
let today = new Date();
let text = `The time and date is ${today.toLocaleString()}`;

(back to table of contents)

Destructuring

Destructuring allows us to extract values from arrays and objects (even deeply nested) and store them in variables with a more convenient syntax.

Destructuring Arrays

javascript
var arr = [1, 2, 3, 4];
var a = arr[0];
var b = arr[1];
var c = arr[2];
var d = arr[3];
javascript
let [a, b, c, d] = [1, 2, 3, 4];

console.log(a); // 1
console.log(b); // 2

Destructuring Objects

javascript
var luke = { occupation: 'jedi', father: 'anakin' };
var occupation = luke.occupation; // 'jedi'
var father = luke.father; // 'anakin'
javascript
let luke = { occupation: 'jedi', father: 'anakin' };
let {occupation, father} = luke;

console.log(occupation); // 'jedi'
console.log(father); // 'anakin'

(back to table of contents)

Modules

Prior to ES6, we used libraries such as Browserify to create modules on the client-side, and require in Node.js. With ES6, we can now directly use modules of all types (AMD and CommonJS).

Exporting in CommonJS

javascript
module.exports = 1;
module.exports = { foo: 'bar' };
module.exports = ['foo', 'bar'];
module.exports = function bar () {};

Exporting in ES6

With ES6, we have various flavors of exporting. We can perform Named Exports:

javascript
export let name = 'David';
export let age  = 25;​​

As well as exporting a list of objects:

javascript
function sumTwo(a, b) {
    return a + b;
}

function sumThree(a, b, c) {
    return a + b + c;
}

export { sumTwo, sumThree };

We can also export functions, objects and values (etc.) simply by using the export keyword:

javascript
export function sumTwo(a, b) {
    return a + b;
}

export function sumThree(a, b, c) {
    return a + b + c;
}

And lastly, we can export default bindings:

javascript
function sumTwo(a, b) {
    return a + b;
}

function sumThree(a, b, c) {
    return a + b + c;
}

let api = {
    sumTwo,
    sumThree
};

export default api;

/* Which is the same as
 * export { api as default };
 */

Best Practices: Always use the export default method at the end of the module. It makes it clear what is being exported, and saves time by having to figure out what name a value was exported as. More so, the common practice in CommonJS modules is to export a single value or object. By sticking to this paradigm, we make our code easily readable and allow ourselves to interpolate between CommonJS and ES6 modules.

Importing in ES6

ES6 provides us with various flavors of importing. We can import an entire file:

javascript
import 'underscore';

It is important to note that simply importing an entire file will execute all code at the top level of that file.

Similar to Python, we have named imports:

javascript
import { sumTwo, sumThree } from 'math/addition';

We can also rename the named imports:

javascript
import {
    sumTwo as addTwoNumbers,
    sumThree as sumThreeNumbers
} from 'math/addition';

In addition, we can import all the things (also called namespace import):

javascript
import * as util from 'math/addition';

Lastly, we can import a list of values from a module:

javascript
import * as additionUtil from 'math/addition';
const { sumTwo, sumThree } = additionUtil;

Importing from the default binding like this:

javascript
import api from 'math/addition';
// Same as: import { default as api } from 'math/addition';

While it is better to keep the exports simple, but we can sometimes mix default import and mixed import if needed. When we are exporting like this:

javascript
// foos.js
export { foo as default, foo1, foo2 };

We can import them like the following:

javascript
import foo, { foo1, foo2 } from 'foos';

When importing a module exported using commonjs syntax (such as React) we can do:

javascript
import React from 'react';
const { Component, PropTypes } = React;

This can also be simplified further, using:

javascript
import React, { Component, PropTypes } from 'react';

Note: Values that are exported are bindings, not references. Therefore, changing the binding of a variable in one module will affect the value within the exported module. Avoid changing the public interface of these exported values.

(back to table of contents)

Parameters

In ES5, we had varying ways to handle functions which needed default values, indefinite arguments, and named parameters. With ES6, we can accomplish all of this and more using more concise syntax.

Default Parameters

javascript
function addTwoNumbers(x, y) {
    x = x || 0;
    y = y || 0;
    return x + y;
}

In ES6, we can simply supply default values for parameters in a function:

javascript
functio

Issues· 7 open

View all issuesOpen on GitHub
  • #24

    Add Proxy support

    help wantedUpdated Mar 20, 2025
  • #94

    Extra space in English cheatsheet

    Updated Oct 8, 2022
  • #84

    Blocks description is misleading

    Updated Feb 7, 2018
  • #86

    I think let and const will actually be hoisted in their scope

    Updated Feb 18, 2017
  • #87

    Getters and setters are not part of ES6

    Updated Feb 18, 2017

> Tags

JavaScriptcheatsheetes6-javascriptjavascript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedOct 2, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言