- ECMAScript 5 (ES5): The 5th edition of ECMAScript, standardized in 2009. This standard has been implemented fairly completely in all modern browsers
- ECMAScript 6 (ES6)/ ECMAScript 2015 (ES2015): The 6th edition of ECMAScript, standardized in 2015. This standard has been partially implemented in most modern browsers.
Here are some key differences between ES5 and ES6:
- Arrow functions & string interpolation:
Consider:
const greetings = (name) => {
return `hello ${name}`;
}
and even:
const greetings = name => `hello ${name}`;
- Const.
Const works like a constant in other languages in many ways but there are some caveats. Const stands for ‘constant reference’ to a value. So with const, you can actually mutate the properties of an object being referenced by the variable. You just can’t change the reference itself.
const NAMES = [];
NAMES.push("Jim");
console.log(NAMES.length === 1); // true
NAMES = ["Steve", "John"]; // error
- Block-scoped variables.
The new ES6 keywordlet
allows developers to scope variables at the block level.Let
doesn’t hoist in the same wayvar
does. - Default parameter values Default parameters allow us to initialize functions with default values. A default is used when an argument is either omitted or undefined — meaning null is a valid value.
// Basic syntax
function multiply (a, b = 2) {
return a * b;
}
multiply(5); // 10
- Class Definition and Inheritance
ES6 introduces language support for classes (class
keyword), constructors (constructor
keyword), and theextend
keyword for inheritance. - for-of operator
The for…of statement creates a loop iterating over iterable objects. - Spread Operator For objects merging
const obj1 = { a: 1, b: 2 }
const obj2 = { a: 2, c: 3, d: 4}
const obj3 = {...obj1, ...obj2}
- Promises
Promises provide a mechanism to handle the results and errors from asynchronous operations. You can accomplish the same thing with callbacks, but promises provide improved readability via method chaining and succinct error handling.
const isGreater = (a, b) => {
return new Promise ((resolve, reject) => {
if(a > b) {
resolve(true)
} else {
reject(false)
}
})
}
isGreater(1, 2)
.then(result => {
console.log('greater')
})
.catch(result => {
console.log('smaller')
})
- Modules exporting & importing Consider module exporting:
const myModule = { x: 1, y: () => { console.log('This is ES5') }}
export default myModule;
and importing:
import myModule from './myModule';