23
loading...
This website collects cookies to deliver better user experience
3
. If not, it will complain about a syntax error.let [two, three] = [2, 3];
two + three;
package.json
with the following content:{
"name": "es6-demo",
"scripts": {
"build": "webpack --watch"
},
"devDependencies": {
"babel-cli": "^6.8.0",
"babel-core": "^6.8.0",
"babel-loader": "^6.2.4",
"babel-plugin-transform-runtime": "^6.8.0",
"babel-preset-es2015": "^6.6.0",
"babel-runtime": "^6.6.1",
"webpack": "^1.13.0"
}
}
webpack.config.js
with the following content:var path = require("path");
module.exports = {
entry: "./src/main.js",
output: {
path: __dirname,
filename: "bundle.js"
},
module: {
loaders: [
{
loader: "babel-loader",
// Compile files in /src directory
include: [path.resolve(__dirname, "src")],
// Babel options
query: {
plugins: ["transform-runtime"],
presets: ["es2015"]
}
}
]
}
};
src
. This folder will contain all of your ES6 code. Let's put a simple script there named main.js
just to test things out.let [one, two, three] = [1, 2, 3];
console.log(`One: ${one}, Two: ${two}, Three: ${three}`);
npm install
npm run build
bundle.js
file in your project folder with the compiled ES5 code. If you open this file, you'll see the ES5 equivalent (in the middle of a bunch of other generated boilerplate):var one = 1;
var two = 2;
var three = 3;
console.log("One: " + one + ", Two: " + two + ", Three: " + three);
npm run build
script is set up to listen for modifications in the src
folder. Now, when you modify the main.js
file, the bundle.js
file will update automatically. You can stop watching with Ctrl
+ C
in the console.npm install
again. When you need to convert your code, you can use npm run build
.Visual Studio Code
, but there are many editors that can be set up to support ES6, such as vim
, Atom
,Sublime Text
, and WebStorm
.math.js
with a toy math library that exports the value of pi and a couple of pi-related functions:export const PI = 3.141592653589793;
export function circumference(r) {
return 2 * PI * r;
}
export function area(r) {
return PI * r * r;
}
import { PI, area } from "./math";
console.log(area(PI));
import * as math from "./math";
console.log(math.area(math.PI));
// reverseString.js
export default function(str) {
return str
.split("")
.reverse()
.join("");
}
// main.js
import reverseString from "./reverseString";
console.log(reverseString("Hello, world!"));
const
is used for constant declarations, and let
is used for variable declarations.const one = 1;
one = 2; // SyntaxError: "one" is read-only
let
is similar to var
, but it fixes a number of quirks about var
that are often stumbling blocks to JavaScript newcomers. In fact, var
has become obsolete at this point because it's let
and const
have assumed its functionality.let
is block-scopedvar
and let
differ in their scoping mechanisms. A variable declared with var
is function-scoped, which means that it is visible anywhere in the surrounding function. Meanwhile, a variable declared with let
is block-scoped, which means it is only visible in its own code block. Calls to the variable outside its code block will lead to errors.// var
console.log(less); // undefined
if (1 < 2) {
var less = true;
console.log(less); // true
}
console.log(less); // true
// let
console.log(less); // Uncaught ReferenceError: less is not defined
if (1 < 2) {
let less = true;
console.log(less); // true
}
console.log(less); // Uncaught ReferenceError: less is not defined
const
also exhibits this block scoping strategy.let
declarations are forbiddenlet
is designed to catch potential assignment mistakes. While duplicate var
declarations will behave like normal reassignment, duplicate let
declarations are not allowed to prevent the common mistake of erroneous reassignment.var x = 1;
var x = 2; // x equals 2
let x = 1;
let x = 2; // SyntaxError: Identifier 'x' has already been declared
let
variables rebound in each loop iterationvar
.for (var i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i);
}, 10);
}
// logs 5 5 5 5 5
i
will be 5 before the first time console.log
is called. When we use let
instead, the i
inside of the function will correspond to the value on that particular iteration of the for-loop.for (let i = 0; i < 5; i++) {
setTimeout(() => {
console.log(i);
}, 10);
}
// logs 0 1 2 3 4
// ES5 way
function Circle(x, y, radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
Circle.prototype.move = function(x, y) {
this.x = x;
this.y = y;
};
Circle.prototype.area = function() {
return Math.PI * Math.pow(this.radius, 2);
};
// ES6 way
class Circle {
constructor(x, y, radius) {
[this.x, this.y, this.radius] = [x, y, radius];
}
move(x, y) {
[this.x, this.y] = [x, y];
}
area() {
return Math.PI * Math.pow(this.radius, 2);
}
}
// ES5 way
function ColoredCircle(x, y, radius, color) {
Circle.call(this, x, y, radius);
this.color = color;
}
ColoredCircle.prototype = Object.create(Circle.prototype);
// ES6 way
class ColoredCircle extends Circle {
constructor(x, y, radius, color) {
super(x, y, radius);
this.color = color;
}
}
var x = 5,
y = 6;
// ES5 way
var coordinate = { x: x, y: y };
// ES6 way
let coordinate = { x, y };
// ES5 way
var counter = {
count: 0,
increment: function() {
this.count++;
}
};
// ES6 way
let counter = {
count: 0,
increment() {
this.count++;
}
};
var a = 1,
b = 2,
c = 3;
let [a, b, c] = [1, 2, 3];
var personData = ["John", 12, true];
// ES5 way
var name = personData[0],
age = personData[1],
isMale = personData[2];
// ES6 way
let [name, age, isMale] = personData;
// ES5 way
var tmp = a;
a = b;
b = tmp;
// ES6 way
[a, b] = [b, a];
var personData = {
name: "John",
age: 12,
isMale: true
};
// ES5 way
var name = personData.name,
age = personData.age,
isMale: personData.isMale;
// ES6 way
let { name, age, isMale } = personData;
var book = {
title: "A Tale of Two Cities",
dimensions: [12, 8, 3],
author: {
name: "Charles Dickens"
}
};
// ES5 way
var title = book.title,
length = book.dimensions[0],
width = book.dimensions[1],
depth = book.dimensions[2],
name = book.author.name;
// ES6 way
let { title, dimensions: [length, width, depth], author: { name } } = book;
var list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// ES3 way
var sumOfSquares = 0;
for (var i = 0; i < list.length; i++) {
var n = list[i],
square = n * n;
sumOfSquares += square;
}
// ES5 way
var sumOfSquares = list
.map(function(x) {
return x * x;
})
.reduce(function(a, b) {
return a + b;
});
// ES6 way
let sumOfSquares = list.map(x => x * x).reduce((a, b) => a + b);
// ES5 way
window.onclick = function(e) {
if (e.ctrlKey) console.log("Ctrl click");
else console.log("Normal click");
};
// ES6 way
window.onclick = e => {
if (e.ctrlKey) console.log("Ctrl click");
else console.log("Normal click");
};
template strings are delimited by backticks
.var weight = 80,
height = 1.8;
// ES5 way
console.log("You are " + height + "m tall and weigh " + weight + "kg.\n" +
"Your BMI is " + weight / (height * height) + ".");
// ES6 way
console.log(`You are ${height}m tall and weigh ${weight}kg.
Your BMI is ${weight / (height * height)}.`);