ECMAScript 6 is also known as ES6 and ECMAScript 2015.
1. Constants
2. Block Scoped Variables and Functions
var vs let
| function varTest() { |
| var x = 31; |
| if (true) { |
| var x = 71; |
| console.log(x); |
| } |
| console.log(x); |
| } |
| |
| function letTest() { |
| let x = 31; |
| if (true) { |
| let x = 71; |
| console.log(x); |
| } |
| console.log(x); |
| } |
3. Arrow Functions
| |
| var multiply = function(x, y) { |
| return x * y; |
| } |
| |
| |
| var multiply = (x, y) => { return x * y }; |
4. Default Parameter Values
| function multiply(a = 10, b = 20){ |
| return a * b; |
| } |
| console.log(multiply(1,2)); |
| console.log(multiply(1)); |
| console.log(multiply()); |
5. Rest Parameters
| function multiply(...a){ |
| var result = 1; |
| for (let arg in a){ |
| result = result * a[arg]; |
| } |
| return result; |
| } |
| console.log(multiply(5,6)); |
| console.log(multiply(5,6,2)); |
6. String Interpolation
The interpolation only works with the new quote character ` used for template literals. It doesn’t work with strings enclosed in the usual quotes " and '.
| var person = {name: "julie", city: "atlanta"}; |
| console.log(person.name); |
| |
| console.log(`${person.name} lives in ${person.city}`); |
| |
| console.log("${person.name} lives in ${person.city}"); |
| console.log('${person.name} lives in ${person.city}'); |
output
produces this output:
julie
julie lives in atlanta
${person.name} lives in ${person.city}
${person.name} lives in ${person.city}
7. Modules
7.1 Named Exports
Module js file mymath.js
| export const sqrt = Math.sqrt; |
| |
| export function square(x) { |
| return x * x; |
| } |
| |
| export function diag(x, y) { |
| return sqrt(square(x) + square(y)); |
| } |
Usage
| import { square, diag } from 'mymath'; |
| |
| console.log(square(11)); // print 121 |
| console.log(diag(4, 3)); // print 5 |
7.2 Default Exports
Module js file mymath.js
| export default function square(x) { |
| return x * x; |
| } |
usage, the name sq
doesn’t match the function in the module. Using default exports allows you to use “nicknames”.
| import sq from 'mymath'; |
| sq(); |
8. Reference