Modules
Before ES2015, there were at least 3 major modules competing standards, which fragmented the community:
- AMD
- RequireJS
- CommonJS
ES2015 standardized these into a common format.
Importing modules
Importing is done via the import ... from ... construct:
import * from 'mymodule'import React from 'react'import { React, Component } from 'react'import React as MyLibrary from 'react'
Exporting modules
You can write modules and export anything to other modules using the export keyword:
export var foo = 2export function bar() { /* ... */ }
Multiline strings
ES2015 introduced a new way to define a string, using backticks.
This allows to write multiline strings very easily:
const str = `OneTwoThree`
Compare it to pre-ES2015:
var str = 'One\n' +'Two\n' +'Three'
Template Literals
Template literals are a way to embed expressions into strings, effectively interpolating the values.
const var = 'test'const string = `something ${var}` //something test
You can perform more complex expressions as well:
const string = `something ${1 + 2 + 3}`const string2 = `something ${foo() ? 'x' : 'y' }`
Default parameters
Functions now support default parameters:
const foo = function(index = 0, testing = true) { /* ... */ }foo()
Destructuring assignments
Given an object, you can extract just some values and put them into named variables:
const person = {firstName: 'Tom',lastName: 'Cruise',actor: true,age: 54, //made up }const {firstName: name, age} = person
name and age contain the desired values.
The syntax also works on arrays:
const a = [1,2,3,4,5][first, second, , , fifth] = a
Enhanced Object Literals
In ES2015 Object Literals gained superpowers.
Simpler syntax to include variables
Instead of doing
const something = 'y'const x = {something: something}
you can do
const something = 'y'const x = {something}
Prototype
A prototype can be specified with
const anObject = { y: 'y' }const x = {__proto__: anObject}
super()
const anObject = { y: 'y', test: () => 'zoo' }const x = {__proto__: anObject,test() {return super.test() + 'x'}}x.test() //zoox
Dynamic properties
const x = {['a' + '_' + 'b']: 'z'}x.a_b //z
For-of loop
ES5 back in 2009 introduced forEach() loops. While nice, they offered no way to break, like for loops always did.
ES2015 introduced the for-of loop, which combines the consineness of forEach with the ability to break:
//iterate over the valuefor (const v of ['a', 'b', 'c']) {console.log(v);}//get the index as well, using `entries()`for (const [i, v] of ['a', 'b', 'c'].entries()) {console.log(i, v);}