📖
Maissen's Grimoire
  • Maissen's Grimoire
  • Html and css grimoire
    • HTML5 Periodical Table
    • HTML Cheat Sheet
    • CSS Cheatsheets
  • Javascript Grimoire
    • JavaScript Cheat Sheet
      • Javascript Array in depth
      • Tagged Template Literals
      • Guard Clauses - The Best Way To Write Complex Conditional Logic
      • JavaScript Optional Chaining
      • JavaScript Null Coalesce
      • What Are Magic Numbers And Why Are They Bad
      • ES6/ECMAScript2015 Cheatsheet
      • First-class and Higher Order Functions: Effective Functional JavaScript
    • Useful JavaScript Tips, Tricks and Best Practices
    • Bits of code
    • Useful JavaScript libraries
      • Components
      • Animation
      • Maps
      • Helpers
      • Presentations
      • Charts
      • Games
      • Audio
      • Images
      • Video
    • Js the right way
  • Angular Grimoire
    • Angular doc
    • Getting Started
    • Angular clean architecture
    • Angular Cheat Sheet
    • TypeScript Cheat Sheet
    • My Favorite Tips and Tricks in Angular
    • NgRx: tips & tricks
    • Bits of code
      • Execute Multiple HTTP Requests in Angular
      • Authentification
        • Angular 8 JWT Authentication with HttpInterceptor and Router
      • Integrations
        • Spring Boot
          • Rest Example
            • Angular,Spring Boot,Spring Data and Rest Example(CRUD)
          • Authentification
            • Angular, Spring Boot: JWT Authentication with Spring Security example
            • Angular Spring Boot Security Oauth2
              • Spring Boot OAUTH2 Role-Based Authorization
              • Spring Boot Security Google Oauth
              • Spring Security OAuth2 User Registration
    • Most used dependency
  • Node Grimoire
    • Express.js 4 Cheatsheet
    • Useful Dependencies
    • How To Use And Write Express Middleware
    • Node.js with SQL databases
      • Node.js Token Based Authentication & Authorization example
      • Node.js Rest APIs example with Express, Sequelize & MySQL
      • Node.js Express & PostgreSQL: CRUD Rest APIs example with Sequelize
      • Sequelize
        • Sequelize Many-to-Many Association example – Node.js & MySQL
        • Sequelize One-to-Many Association example with Node.js & MySQL
    • Node.js with NOSQL databases
      • Node.js + MongoDB: User Authentication & Authorization with JWT
      • Node.js, Express & MongoDb: Build a CRUD Rest Api example
      • MongoDB One-to-One relationship tutorial with Mongoose example
      • MongoDB One-to-Many Relationship tutorial with Mongoose examples
      • MongoDB Many-to-Many Relationship with Mongoose examples
  • Upload files
    • How to upload multiple files in Node.js
    • Upload & resize multiple images in Node.js using Express, Multer, Sharp
    • Upload/store images in MySQL using Node.js, Express & Multer
    • How to upload/store images in MongoDB using Node.js, Express & Multer
  • React Grimoire
    • React Doc
    • React Grimoire
    • React Cheat Sheet
  • spring boot Grimoire
    • Getting started
    • Spring Boot, Spring Data JPA – Rest CRUD API example
    • Spring Boot Token based Authentication with Spring Security & JWT
  • Mongo Grimoire
    • MongoDb-Mongoose Cheat Sheet
  • Development tools
    • Design Patterns
  • maissen_grimoire
Powered by GitBook
On this page
  • Installation
  • Usage
  • Default Parameters in ES6
  • Template Literals in ES6
  • Multi-line Strings in ES6
  • Destructuring Assignment in ES6
  • Enhanced Object Literals in ES6
  • Arrow Functions in ES6
  • Promises in ES6
  • Block-Scoped Constructs Let and Const
  • Classes in ES6
  • Modules in ES6
  • More ES6 Features
  • Resources

Was this helpful?

  1. Javascript Grimoire
  2. JavaScript Cheat Sheet

ES6/ECMAScript2015 Cheatsheet

Installation

Babel:

  • CLI: $ npm install -g babel-cli

  • Require: $ npm install -g babel-core

  • Browser: <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.js"></script>

  • Gulp: $ npm install --save-dev gulp-babel

Usage

  • CLI: $ babel script.js or $ babel script.js

  • Require: require("babel-core/register");

  • Browser: <script type="text/babel"></script>

Gulp:

var gulp = require('gulp'),
  babel = require('gulp-babel')

gulp.task('build', function () {
  return gulp.src('src/app.js')
    .pipe(babel())
    .pipe(gulp.dest('build'))
})

Default Parameters in ES6

var link = function(height = 50, color = 'red', url = 'http://azat.co') {
  ...
}

Template Literals in ES6

var name = `Your name is ${first} ${last}.`
var url = `http://localhost:3000/api/messages/${id}`

Multi-line Strings in ES6

var roadPoem = `Then took the other, as just as fair,
	And having perhaps the better claim
	Because it was grassy and wanted wear,
	Though as for that the passing there
	Had worn them really about the same,`

var fourAgreements = `You have the right to be you.
	You can only be you when you do your best.`

Destructuring Assignment in ES6

var { house, mouse} = $('body').data() // we'll get house and mouse variables

var {json} = require('body-parser')

var {username, password} = req.body

var [col1, col2]  = $('.column'),
  [line1, line2, line3, , line5] = file.split('\n')

Enhanced Object Literals in ES6

var serviceBase = {port: 3000, url: 'azat.co'},
    getAccounts = function(){return [1,2,3]}
var accountService = {
    __proto__: serviceBase,
    getAccounts,
    toString() {
     return JSON.stringify((super.valueOf()))
    },
	getUrl() {return "http://" + this.url + ':' + this.port},
    [ 'valueOf_' + getAccounts().join('_') ]: getAccounts()
};
console.log(accountService)    

Arrow Functions in ES6

$('.btn').click((event) =>{
  this.sendData()
})
var logUpperCase = function() {
  this.string = this.string.toUpperCase()
  return () => console.log(this.string)
}

logUpperCase.call({ string: 'es6 rocks' })()
var ids = ['5632953c4e345e145fdf2df8','563295464e345e145fdf2df9']
var messages = ids.map(value => `ID is ${value}`) // implicit return
var ids = ['5632953c4e345e145fdf2df8','563295464e345e145fdf2df9']
var messages = ids.map((value, index, list) => `ID of ${index} element is ${value} `) // implicit return

Promises in ES6

var wait1000 = new Promise((resolve, reject)=> {
  setTimeout(resolve, 1000)
}).then(()=> {
  console.log('Yay!')
})
var wait1000 = ()=> new Promise((resolve, reject)=> {setTimeout(resolve, 1000)})

wait1000()
    .then(function() {
        console.log('Yay!')
        return wait1000()
    })
    .then(function() {
        console.log('Wheeyee!')
    });

Block-Scoped Constructs Let and Const

function calculateTotalAmount (vip) {
  var amount = 0 // probably should also be let, but you can mix var and let
  if (vip) {
    let amount = 1 // first amount is still 0
  }
  { // more crazy blocks!
    let amount = 100 // first amount is still 0
    {
      let amount = 1000 // first amount is still 0
      }
  }  
  return amount
}

console.log(calculateTotalAmount(true))
function calculateTotalAmount (vip) {
  const amount = 0  
  if (vip) {
    const amount = 1
  }
  { // more crazy blocks!
    const amount = 100
    {
      const amount = 1000
      }
  }  
  return amount
}

console.log(calculateTotalAmount(true))

Classes in ES6

class baseModel {
  constructor(options = {}, data = []) { // class constructor
		this.name = 'Base'
    this.url = 'http://azat.co/api'
		this.data = data
    this.options = options
	}

	getName() { // class method
		console.log(`Class name: ${this.name}`)
	}
}

class AccountModel extends baseModel {
	constructor(options, data) {
    super({private: true}, ['32113123123', '524214691']) //call the parent method with super
		this.name = 'Account Model'
    this.url +='/accounts/'
	}
	get accountsData() { //calculated attribute getter
    // ... make XHR
		return this.data
	}
}

let accounts = new AccountModel(5)
accounts.getName()
console.log('Data is %s', accounts.accountsData)

The output is:

Class name: Account Model
Data is %s 32113123123,524214691

Modules in ES6

module.js file:

export var port = 3000
export function getAccounts(url) {
 ...
}

main.js file:

import {port, getAccounts} from 'module'
console.log(port) // 3000

Or import everything as a variable service in main.js:

import * as service from 'module'
console.log(service.port) // 3000

More ES6 Features

  1. New Math, Number, String, Array and Object methods

  2. Binary and octal number types

  3. Default rest spread

  4. For of comprehensions (hello again mighty CoffeeScript!)

  5. Symbols

  6. Tail calls

  7. Generators

  8. New data structures like Map and Set

Resources

PreviousWhat Are Magic Numbers And Why Are They BadNextFirst-class and Higher Order Functions: Effective Functional JavaScript

Last updated 5 years ago

Was this helpful?

by By Kyle Simpson

Learn ES2015
ES6 REPL
ES6 Fiddle
Understanding ECMAScript 6 by Nicolas Zakas book
Exploring ES6 by Dr. Axel Rauschmayer
You Don't Know JS: ES6 & Beyond