This is to compare the difference between ECMAScript 6 and ECMAScript 5
Use ECMAScript 6 you could reduced lots code , but the core problem is not all the browser support, to resolve this ECMAScript 6 need to use a compiler to transform your ECMAScript 6 code to ECMAScript 5 compatible code, in this purpose you could use Babel which allowed you run in current browsers
As follow is introduced some syntax that I used often in ES5 and it’s completely shorten in ES6
Before you should know the difference between var, let and const
compare to var, let will be more strict but it also changeable in the block scope,
const in the word means it is immutable, try in browser to defined between then you could find the error notice once you had declared with let and const, this could be more easy to debug since it’s more strict compare var
you could get more introduction here
1 Constants
ES5
// only in ES5 through the help of object properties // and only in global context and not in a block scope Object.defineProperty(typeof global === "object" ? global : window, "PI", { value: 3.141593, enumerable: true, writable: false, configurable: false }) PI > 3.0;
ES6
const PI = 3.141593 PI > 3.0
In ES6 you could defined the constant, variables which cannot be re-assigned new content, but in case the content is an object, this means the object itself can still be altered: ( follow as resign value and it show error, but property in object can be added or removed or be changed) :
2 Scoping: Block-scoped Variables
without hoisting, so you do not need to declare variable to the top of the current script or the current function
ES5
var i, x, y; for (i = 0; i < a.length; i++) { x = a[i]; … } for (i = 0; i < b.length; i++) { y = b[i]; … } var callbacks = []; for (var i = 0; i <= 2; i++) { (function (i) { callbacks[i] = function() { return i * 2; }; })(i); } callbacks[0]() === 0; callbacks[1]() === 2; callbacks[2]() === 4;
ES6
for (let i = 0; i < a.length; i++) { let x = a[i] … } for (let i = 0; i < b.length; i++) { let y = b[i] … } let callbacks = [] for (let i = 0; i <= 2; i++) { callbacks[i] = function () { return i * 2 } } callbacks[0]() === 0 callbacks[1]() === 2 callbacks[2]() === 4
3 Arrow Functions, which reduced funtion expressive closure syntax
ES5
odds = evens.map(function (v) { return v + 1; }); pairs = evens.map(function (v) { return { even: v, odd: v + 1 }; }); nums = evens.map(function (v, i) { return v + i; });
ES6
odds = evens.map(v => v + 1) pairs = evens.map(v => ({ even: v, odd: v + 1 })) nums = evens.map((v, i) => v + i)
and so does statement bodies:
ES5
nums.forEach(function (v) { if (v % 5 === 0) fives.push(v); });
ES6
nums.forEach(v => { if (v % 5 === 0) fives.push(v) })
Lexical this
ES5
// variant 1 var self = this; this.nums.forEach(function (v) { if (v % 5 === 0) self.fives.push(v); }); // variant 2 this.nums.forEach(function (v) { if (v % 5 === 0) this.fives.push(v); }, this); // variant 3 (since ECMAScript 5.1 only) this.nums.forEach(function (v) { if (v % 5 === 0) this.fives.push(v); }.bind(this));
ES6
this.nums.forEach((v) => { if (v % 5 === 0) this.fives.push(v) })
3 Extended Parameter Handling
ES6 could be like other functional programme lauguage, you could simple and intuitive default values in your function parameters:
ES5
function f (x, y, z) { if (y === undefined) y = 7; if (z === undefined) z = 42; return x + y + z; }; f(1) === 50;
ES6
function f (x, y = 7, z = 42) { return x + y + z } f(1) === 50
And you could use aggregation of remaining arguments into single parameter of variadic functions, aggregation is quiet useful in Reactjs
ES5
function f (x, y) { var a = Array.prototype.slice.call(arguments, 2); return (x + y) * a.length; }; f(1, 2, "hello", true, 7) === 9;
ES6
function f (x, y, ...a) { return (x + y) * a.length } f(1, 2, "hello", true, 7) === 9
Spreading of elements in an array or a string into both literal elements:
ES5
var params = [ "hello", true, 7 ]; var other = [ 1, 2 ].concat(params); // [ 1, 2, "hello", true, 7 ]
ES6
var params = [ "hello", true, 7 ] var other = [ 1, 2, ...params ] // [ 1, 2, "hello", true, 7 ]
Template Literals
String Interpolation for output of defined variables, this is quiet useful once you had lots string to express, for example show error message string in JS:
instead of using “+ card.amount +” , used ${card.amount} is more readable
ES5
var customer = { name: "Foo" }; var card = { amount: 7, product: "Bar", unitprice: 42 }; var message = "Hello " + customer.name + ",\n" + "want to buy " + card.amount + " " + card.product + " for\n" + "a total of " + (card.amount * card.unitprice) + " bucks?";
ES6
var customer = { name: "Foo" } var card = { amount: 7, product: "Bar", unitprice: 42 } var message = `Hello ${customer.name}, want to buy ${card.amount} ${card.product} for a total of ${card.amount * card.unitprice} bucks?`
Enhanced Object Properties
Property Shorthand:
ES5
var x = 0, y = 0; obj = { x: x, y: y };
ES6
var x = 0, y = 0 obj = { x, y }
Computed Property Names
ES5
var obj = { foo: "bar" }; obj[ "baz" + quux() ] = 42;
ES6
let obj = { foo: "bar", [ "baz" + quux() ]: 42 }
Class definition
like other OOP functional language, ES6 could be more intuitive, OOP-style and boilerplate-free classes, if you write php then you will love this point
ES5
var Shape = function (id, x, y) { this.id = id; this.move(x, y); }; Shape.prototype.move = function (x, y) { this.x = x; this.y = y; };
ES6
class Shape { constructor (id, x, y) { this.id = id this.move(x, y) } move (x, y) { this.x = x this.y = y } }
New Built-In Methods
Object Property Assignment: assign()
this will return the value of assign target object
ES5
var dest = { quux: 0 }; var src1 = { foo: 1, bar: 2 }; var src2 = { foo: 3, baz: 4 }; Object.keys(src1).forEach(function(k) { dest[k] = src1[k]; }); Object.keys(src2).forEach(function(k) { dest[k] = src2[k]; }); dest.quux === 0; dest.foo === 3; dest.bar === 2; dest.baz === 4;
ES6
var dest = { quux: 0 } var src1 = { foo: 1, bar: 2 } var src2 = { foo: 3, baz: 4 } Object.assign(dest, src1, src2) dest.quux === 0 dest.foo === 3 dest.bar === 2 dest.baz === 4
Array Element Finding
New function for finding an element in an array
ES5
[ 1, 3, 4, 2 ].filter(function (x) { return x > 3; })[0]; // 4 // no equivalent in ES5
ES6
[ 1, 3, 4, 2 ].find(x => x > 3) // 4 [ 1, 3, 4, 2 ].findIndex(x => x > 3) // 2
String Repeating
ES5
Array((4 * depth) + 1).join(" "); Array(3 + 1).join("foo");
ES6
" ".repeat(4 * depth) "foo".repeat(3)
String Searching
New specific string functions to search for a sub-string
ES5
"hello".startsWith("ello", 1) // true "hello".endsWith("hell", 4) // true "hello".includes("ell") // true "hello".includes("ell", 1) // true "hello".includes("ell", 2) // false
ES6
"hello".indexOf("ello") === 1; // true "hello".indexOf("hell") === (4 - "hell".length); // true "hello".indexOf("ell") !== -1; // true "hello".indexOf("ell", 1) !== -1; // true "hello".indexOf("ell", 2) !== -1; // false
Number Truncation
Truncate a floating point number to its integral part, completely dropping the fractional part.
ES5
function mathTrunc (x) { return (x < 0 ? Math.ceil(x) : Math.floor(x)); } console.log(mathTrunc(42.7)) // 42 console.log(mathTrunc( 0.1)) // 0 console.log(mathTrunc(-0.1)) // -0
ES6
console.log(Math.trunc(42.7)) // 42 console.log(Math.trunc( 0.1)) // 0 console.log(Math.trunc(-0.1)) // -0