DEV Community

Cover image for ES6 Cheatsheet 🔥 - All You Need 🚀
Garvit Motwani for World In Dev

Posted on • Updated on

ES6 Cheatsheet 🔥 - All You Need 🚀

Hey Devs, This is an all you need ES6 cheatsheet for beginners and seasoned developers!

So let's get started!!

 

🎉 Giveaway

We are giving away any course you need on Udemy. Any price any course.
To enter you have to do the following:

  1. 👍 React to this post
  2. ✉️ Subscribe to our newsletter

--> Grab the downloadable PDF version here

Block scoping

Let

function fn () {
  let x = 0
  if (true) {
    let x = 1 // only inside this `if`
  }
}
Enter fullscreen mode Exit fullscreen mode

Const

const a = 1
Enter fullscreen mode Exit fullscreen mode

let is the new var. Constants work just like let, but can't be reassigned.
Check: Let and const

Backtick strings

Interpolation

const message = `Hello ${name}`
Enter fullscreen mode Exit fullscreen mode

Multiline strings

const str = `
hello
world
`
Enter fullscreen mode Exit fullscreen mode

Templates and multiline strings.
Check: Template strings

Binary and octal literals

let bin = 0b1010010
let oct = 0o755
Enter fullscreen mode Exit fullscreen mode

Check: Binary and octal literals

New methods

New string methods

"hello".repeat(3)
"hello".includes("ll")
"hello".startsWith("he")
"hello".padStart(8) // "   hello"
"hello".padEnd(8) // "hello   " 
"hello".padEnd(8, '!') // hello!!!
"\u1E9B\u0323".normalize("NFC")
Enter fullscreen mode Exit fullscreen mode

Check: New methods

Classes

class Circle extends Shape {
Enter fullscreen mode Exit fullscreen mode

Constructor

  constructor (radius) {
    this.radius = radius
  }
Enter fullscreen mode Exit fullscreen mode

Methods

  getArea () {
    return Math.PI * 2 * this.radius
  }
Enter fullscreen mode Exit fullscreen mode

Calling superclass methods

  expand (n) {
    return super.expand(n) * Math.PI
  }
Enter fullscreen mode Exit fullscreen mode

Static methods

  static createFromDiameter(diameter) {
    return new Circle(diameter / 2)
  }
}
Enter fullscreen mode Exit fullscreen mode

Syntactic sugar for prototypes.
Check: Classes

Exponent operator

const byte = 2 ** 8
// Same as: Math.pow(2, 8)
Enter fullscreen mode Exit fullscreen mode

Promises

Making promises

new Promise((resolve, reject) => {
  if (ok) { resolve(result) }
  else { reject(error) }
})
Enter fullscreen mode Exit fullscreen mode

For asynchronous programming.
Check: Promises

Using promises

promise
  .then((result) => { ··· })
  .catch((error) => { ··· })
Enter fullscreen mode Exit fullscreen mode

Using promises with finally

promise
  .then((result) => { ··· })
  .catch((error) => { ··· })
  .finally(() => { // logic independent of success/error })
Enter fullscreen mode Exit fullscreen mode

The handler is called when the promise is fulfilled or rejected.

Promise functions

Promise.all(···)
Promise.race(···)
Promise.reject(···)
Promise.resolve(···)
Enter fullscreen mode Exit fullscreen mode

Async-await

async function run () {
  const user = await getUser()
  const tweets = await getTweets(user)
  return [user, tweets]
}
Enter fullscreen mode Exit fullscreen mode

async functions are another way of using functions.

Check: async function

Destructuring

Destructuring assignment

Arrays

const [first, last] = ['Nikola', 'Tesla']
Enter fullscreen mode Exit fullscreen mode

Objects

let {title, author} = {
  title: 'The Silkworm',
  author: 'R. Galbraith'
}
Enter fullscreen mode Exit fullscreen mode

Supports for matching arrays and objects.
Check: Destructuring

Default values

const scores = [22, 33]
const [math = 50, sci = 50, arts = 50] = scores
Enter fullscreen mode Exit fullscreen mode
// Result:
// math === 22, sci === 33, arts === 50
Enter fullscreen mode Exit fullscreen mode

Default values can be assigned while destructuring arrays or objects.

Function arguments

function greet({ name, greeting }) {
  console.log(`${greeting}, ${name}!`)
}
Enter fullscreen mode Exit fullscreen mode
greet({ name: 'Larry', greeting: 'Ahoy' })
Enter fullscreen mode Exit fullscreen mode

Destructuring of objects and arrays can also be done in function arguments.

Default values

function greet({ name = 'Rauno' } = {}) {
  console.log(`Hi ${name}!`);
}
Enter fullscreen mode Exit fullscreen mode
greet() // Hi Rauno!
greet({ name: 'Larry' }) // Hi Larry!
Enter fullscreen mode Exit fullscreen mode

Reassigning keys

function printCoordinates({ left: x, top: y }) {
  console.log(`x: ${x}, y: ${y}`)
}
Enter fullscreen mode Exit fullscreen mode
printCoordinates({ left: 25, top: 90 })
Enter fullscreen mode Exit fullscreen mode

This example assigns x to the value of the left key.

Loops

for (let {title, artist} of songs) {
  ···
}
Enter fullscreen mode Exit fullscreen mode

The assignment expressions work in loops, too.

Object destructuring

const { id, ...detail } = song;
Enter fullscreen mode Exit fullscreen mode

Extract some keys individually and remaining keys in the object using rest (...) operator

Spread

Object spread

with Object spread

const options = {
  ...defaults,
  visible: true
}
Enter fullscreen mode Exit fullscreen mode

without Object spread

const options = Object.assign(
  {}, defaults,
  { visible: true })
Enter fullscreen mode Exit fullscreen mode

The Object spread operator lets you build new objects from other objects.

Check: Object spread

Array spread

with Array spread

const users = [
  ...admins,
  ...editors,
  'rstacruz'
]
Enter fullscreen mode Exit fullscreen mode

without Array spread

const users = admins
  .concat(editors)
  .concat([ 'rstacruz' ])
Enter fullscreen mode Exit fullscreen mode

The spread operator lets you build new arrays in the same way.

Check: Spread operator

Functions

Function arguments

Default arguments

function greet (name = 'Jerry') {
  return `Hello ${name}`
}
Enter fullscreen mode Exit fullscreen mode

Rest arguments

function fn(x, ...y) {
  // y is an Array
  return x * y.length
}
Enter fullscreen mode Exit fullscreen mode

Spread

fn(...[1, 2, 3])
// same as fn(1, 2, 3)
Enter fullscreen mode Exit fullscreen mode

Default, rest, spread.
Check: Function arguments

Fat arrows

Fat arrows

setTimeout(() => {
  ···
})
Enter fullscreen mode Exit fullscreen mode

With arguments

readFile('text.txt', (err, data) => {
  ...
})
Enter fullscreen mode Exit fullscreen mode

Implicit return

numbers.map(n => n * 2)
// No curly braces = implicit return
// Same as: numbers.map(function (n) { return n * 2 })
numbers.map(n => ({
  result: n * 2
}))
// Implicitly returning objects requires parentheses around the object
Enter fullscreen mode Exit fullscreen mode

Like functions but with this preserved.
Check: Fat arrows

Objects

Shorthand syntax

module.exports = { hello, bye }
// Same as: module.exports = { hello: hello, bye: bye }
Enter fullscreen mode Exit fullscreen mode

Check: Object literal enhancements

Methods

const App = {
  start () {
    console.log('running')
  }
}
// Same as: App = { start: function () {···} }
Enter fullscreen mode Exit fullscreen mode

Check: Object literal enhancements

Getters and setters

const App = {
  get closed () {
    return this.status === 'closed'
  },
  set closed (value) {
    this.status = value ? 'closed' : 'open'
  }
}
Enter fullscreen mode Exit fullscreen mode

Check: Object literal enhancements

Computed property names

let event = 'click'
let handlers = {
  [`on${event}`]: true
}
// Same as: handlers = { 'onclick': true }
Enter fullscreen mode Exit fullscreen mode

Check: Object literal enhancements

Extract values

const fatherJS = { age: 57, name: "Brendan Eich" }

Object.values(fatherJS)
// [57, "Brendan Eich"]
Object.entries(fatherJS)
// [["age", 57], ["name", "Brendan Eich"]]
Enter fullscreen mode Exit fullscreen mode

Modules

Imports

import 'helpers'
// aka: require('···')
Enter fullscreen mode Exit fullscreen mode
import Express from 'express'
// aka: const Express = require('···').default || require('···')
Enter fullscreen mode Exit fullscreen mode
import { indent } from 'helpers'
// aka: const indent = require('···').indent
Enter fullscreen mode Exit fullscreen mode
import * as Helpers from 'helpers'
// aka: const Helpers = require('···')
Enter fullscreen mode Exit fullscreen mode
import { indentSpaces as indent } from 'helpers'
// aka: const indent = require('···').indentSpaces
Enter fullscreen mode Exit fullscreen mode

import is the new require().
Check: Module imports

Exports

export default function () { ··· }
// aka: module.exports.default = ···
Enter fullscreen mode Exit fullscreen mode
export function mymethod () { ··· }
// aka: module.exports.mymethod = ···
Enter fullscreen mode Exit fullscreen mode
export const pi = 3.14159
// aka: module.exports.pi = ···
Enter fullscreen mode Exit fullscreen mode

export is the new module.exports.
Check: Module exports

Generators

Generators

function* idMaker () {
  let id = 0
  while (true) { yield id++ }
}
Enter fullscreen mode Exit fullscreen mode
let gen = idMaker()
gen.next().value  // → 0
gen.next().value  // → 1
gen.next().value  // → 2
Enter fullscreen mode Exit fullscreen mode

It's complicated.
Check: Generators

For..of iteration

for (let i of iterable) {
  ···
}
Enter fullscreen mode Exit fullscreen mode

For iterating through generators and arrays.
Check: For..of iteration

References

MDN Web Docs
DevHints
w3schools

⚡️ Giveaway ⚡️

We are giving away any course you need on Udemy. Any price any course.
Steps to enter the giveaway
--> React to this post
--> Subscribe to our Newsletter <-- Very important
--> Follow me on Twitter <-- x2 Chances of winning

The winner will be announced on May 1, Via Twitter


Thank you very much for reading this article.

Comment any tricks & tips you know!

PLEASE LIKE, SHARE, AND COMMENT

Follow me on Dev and Twitter


Read also:

Subscribe to our newsletter to receive our weekly recap directly on your email!

Join us on Discord to participate in hackathons with us / participate in our giveaways!

Thanks for reading!!

Top comments (8)

Collapse
 
shadowtime2000 profile image
Info Comment hidden by post author - thread only accessible via permalink
shadowtime2000

Your description of let and const lacks some detail. Let isn't just "the new var". It has differences. For one part, var is globally scoped as when you do var this = "that" it is kind of linked to globalThis, while let is only available within the scope it was created in.

Collapse
 
kattak2k profile image
Ravi Katta

This is the best cheatsheet, I've come across.

Collapse
 
garvitmotwani profile image
Garvit Motwani

Thanks

Collapse
 
killants profile image
killants

Good post with direct and easy explanation... Thx ;)

Collapse
 
garvitmotwani profile image
Garvit Motwani

Thanks

Collapse
 
madza profile image
Madza

Tbh I miss new ES versions to be as revolutionary as ES6 was back in the day 😉 Nowadays just a couple string or array methods are being introduced 😀

Collapse
 
garvitmotwani profile image
Garvit Motwani

Ya they are not that good

Collapse
 
olsard profile image
olsard

Great, thanks a million for your work.

Some comments have been hidden by the post's author - find out more