Подытожим концептуальные различия:
Функция жирной стрелки (=›)
// ES5 function getNumber() { return 10; } // ES6 const getNumber = () => 10; ----------------------------------- // ES5 function getArray() { return [1, 2, 3]; } // ES6 const getArray = () => [1, 2, 3]; ----------------------------------- // ES5 function getObject() { return { a: 1, b: 2, c: 3 };; } // ES6 const getObj = () => ({ a: 1, b: 2, c: 3 }); -----------------------------------
Манипуляции с объектами
var myObj = { a: 1, b: 2 }; // ES5 var a = myObj.a; var b = myObj.b; // ES6 var { a, b } = myObj; ------------------------------------ var a = 1; var b = 2; // ES5 var myObj = { a: a, b: b }; // ES6 var myObj = { a, b }; ------------------------------------ var myObj1 = { a: 1, b: 2 }; var myObj2 = { c: 3, d: 4 }; // ES5 var myObj3 = Object.assign(myObj1, myObj2); // ES6 var myObj3 = { ...myObj1, ...myObj2 };
Асинхронная функция (обратный вызов или обещание)
// ES5 (callback) function isEvenNumber(num, callback) { if (num % 2 === 0) { callback(true); } else { callback(false); } }isEvenNumber(10, function(result) { if (result) { console.log('even number'); } else { console.log('odd number'); } }); // ES6 (promise) const isEvenNumber = (num) => { return new Promise((resolve, reject) => { if (num % 2 === 0) { resolve(true); } else { reject(false); } }); };isEvenNumber(10).then((result) => { console.log('even number'); }).catch((error) => { console.log('odd number'); });
Экспорт и импорт модуля
Модуль экспорта
var testModule = { a: 1, b: 2 }; // ES5 module.exports = testModule; // ES6 export default testModule; // ES6 (child modules) export const a = 1; export const b = 2;
Модуль импорта
// ES5 var testModule = require(./testModule); // ES6 import testModule from './testModule'; // ES6 (child modules) import { a, b } from './testModule';
Литерал шаблона (`)
const a = 1; const b = 'b'; // ES5 const c = 'value of a is ' + a + ' and value of b is ' + b; // ES6 const c = `value of a is ${a} and value of b is ${b}`;