You are looking for information, articles, knowledge about the topic nail salons open on sunday near me es2015+ on Google, you do not find the information you need! Here are the best content compiled and compiled by the https://chewathai27.com/to team, along with other related topics such as: es2015+ ECMAScript, Babel, Install babel, Babel/preset-es2015, Babel preset es2015 babel 7, Babel plugin, Babel/preset-env, Sự khác nhau giữa ES5 và ES6
Table of Contents
ES6 (ES2015) là gì? Và tìm hiểu những tính năng mới. – Fullstack Station
- Article author: fullstackstation.com
- Reviews from users: 39617
Ratings
- Top rated: 3.6
- Lowest rated: 1
- Summary of article content: Articles about ES6 (ES2015) là gì? Và tìm hiểu những tính năng mới. – Fullstack Station ECMAScript 6/ES6 là phiên bản mới nhất của bộ tiêu chuẩn ECMAScript, được ra mắt vào giữa 2015 là lấy tên chính thức là ES2015. …
- Most searched keywords: Whether you are looking for ES6 (ES2015) là gì? Và tìm hiểu những tính năng mới. – Fullstack Station ECMAScript 6/ES6 là phiên bản mới nhất của bộ tiêu chuẩn ECMAScript, được ra mắt vào giữa 2015 là lấy tên chính thức là ES2015. ECMAScript 6/ES6 là phiên bản mới nhất của bộ tiêu chuẩn ECMAScript, được ra mắt vào giữa 2015 là lấy tên chính thức là ES2015.
- Table of Contents:
ES6 là gì
Các chức năng mới của ES6
![ES6 (ES2015) là gì? Và tìm hiểu những tính năng mới. - Fullstack Station](https://fullstackstation.com/wp-content/uploads/2016/01/a-bright-new-future-is-comming.jpg)
Learn ES2015 · Babel
- Article author: babeljs.io
- Reviews from users: 43227
Ratings
- Top rated: 3.9
- Lowest rated: 1
- Summary of article content: Articles about Learn ES2015 · Babel ES2015 es are syntactic sugar over the prototype-based OO pattern. Having a single convenient declarative form makes patterns easier to use, and … …
- Most searched keywords: Whether you are looking for Learn ES2015 · Babel ES2015 es are syntactic sugar over the prototype-based OO pattern. Having a single convenient declarative form makes patterns easier to use, and …
- Table of Contents:
›Guides
Introduction
ECMAScript 2015 Features
![Learn ES2015 · Babel](https://babeljs.io/img/ogImage.png)
ES2015 | Web | Google Developers
- Article author: developers.google.com
- Reviews from users: 33942
Ratings
- Top rated: 3.8
- Lowest rated: 1
- Summary of article content: Articles about ES2015 | Web | Google Developers ES2015 (formally ES6) is a fantastic step forward for the JavaScript language. It brings new features and sugaring for patterns that … …
- Most searched keywords: Whether you are looking for ES2015 | Web | Google Developers ES2015 (formally ES6) is a fantastic step forward for the JavaScript language. It brings new features and sugaring for patterns that … ES2015 is a fantastic step forward for the JavaScript language. It brings new features and sugaring for patterns that required significant boilerplate in ES5.
- Table of Contents:
Transpilation with Babel
Linting and Style Checks
ES2015 Syntax Highlighting
Documenting ES2015
Authoring Gulpjs files with Babel
Favorite ES2015 Features
Links for More Info
![ES2015 | Web | Google Developers](https://developers.google.com/web/images/social-webfu-16x9.png)
JavaScript ES6
- Article author: www.w3schools.com
- Reviews from users: 35506
Ratings
- Top rated: 3.5
- Lowest rated: 1
- Summary of article content: Articles about JavaScript ES6 ECMAScript 2015 is also known as ES6 and ECMAScript 6. This chapter describes the most important features of ES6. New Features in ES6. The let keyword; The … …
- Most searched keywords: Whether you are looking for JavaScript ES6 ECMAScript 2015 is also known as ES6 and ECMAScript 6. This chapter describes the most important features of ES6. New Features in ES6. The let keyword; The … HTML, Python, CSS, SQL, JavaScript, How to, PHP, Java, C, C++, C#, jQuery, Bootstrap, Colors, W3.CSS, XML, MySQL, Icons, NodeJS, React, Graphics, Angular, R, AI, Git, Data Science, Code Game, Tutorials, Programming, Web Development, Training, Learning, Quiz, Exercises, Courses, Lessons, References, Examples, Learn to code, Source code, Demos, Tips, WebsiteWell organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.
- Table of Contents:
Tutorials
References
Exercises and Quizzes
JS Tutorial
JS Versions
JS Objects
JS Functions
JS Classes
JS Async
JS HTML DOM
JS Browser BOM
JS Web APIs
JS AJAX
JS JSON
JS vs jQuery
JS Graphics
JS Examples
JS References
New Features in ES6
Browser Support for ES6 (2015)
JavaScript let
JavaScript const
Arrow Functions
The ForOf Loop
JavaScript Maps
JavaScript Sets
JavaScript Classes
Using a Class
JavaScript Promises
The Symbol Type
Default Parameter Values
Function Rest Parameter
Stringincludes()
StringstartsWith()
StringendsWith()
Arrayfrom()
Array keys()
Array find()
Array findIndex()
New Math Methods
The Mathtrunc() Method
The Mathsign() Method
The Mathcbrt() Method
The Mathlog2() Method
The Mathlog10() Method
New Number Properties
New Number Methods
The NumberisInteger() Method
The NumberisSafeInteger() Method
New Global Methods
The isFinite() Method
The isNaN() Method
Object entries()
Modules
Report Error
Thank You For Helping Us!
![JavaScript ES6](https://www.w3schools.com/images/w3schools_logo_436_2.png)
ECMAScript 2015 Language Specification – ECMA-262 6th Edition
- Article author: 262.ecma-international.org
- Reviews from users: 22943
Ratings
- Top rated: 3.7
- Lowest rated: 1
- Summary of article content: Articles about ECMAScript 2015 Language Specification – ECMA-262 6th Edition Ecma International. Rue du Rhone 114. CH-1204 Geneva. Tel: +41 22 849 6000. Fax: +41 22 849 6001. Web: http://www.ecma-international.org. COPYRIGHT NOTICE. …
- Most searched keywords: Whether you are looking for ECMAScript 2015 Language Specification – ECMA-262 6th Edition Ecma International. Rue du Rhone 114. CH-1204 Geneva. Tel: +41 22 849 6000. Fax: +41 22 849 6001. Web: http://www.ecma-international.org. COPYRIGHT NOTICE.
- Table of Contents:
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Supplemental Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Supplemental Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Supplemental Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
![ECMAScript 2015 Language Specification – ECMA-262 6th Edition](https://i0.wp.com/wpsites.net/wp-content/uploads/2014/06/icon-after-more-link.png)
ECMAScript 2015 Language Specification – ECMA-262 6th Edition
- Article author: tharong.com
- Reviews from users: 48458
Ratings
- Top rated: 4.8
- Lowest rated: 1
- Summary of article content: Articles about ECMAScript 2015 Language Specification – ECMA-262 6th Edition ECMAScript 6 (hay còn được gọi là ES6, ES2015) là phiên bản mới nhất của chuẩn ECMAScript. Chuẩn này được phê duyệt vào tháng 6/2015. Nó là một bản nâng cấp … …
- Most searched keywords: Whether you are looking for ECMAScript 2015 Language Specification – ECMA-262 6th Edition ECMAScript 6 (hay còn được gọi là ES6, ES2015) là phiên bản mới nhất của chuẩn ECMAScript. Chuẩn này được phê duyệt vào tháng 6/2015. Nó là một bản nâng cấp …
- Table of Contents:
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Supplemental Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Supplemental Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Supplemental Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
Syntax
![ECMAScript 2015 Language Specification – ECMA-262 6th Edition](https://i0.wp.com/wpsites.net/wp-content/uploads/2014/06/icon-after-more-link.png)
ECMAScript – Wikipedia
- Article author: en.wikipedia.org
- Reviews from users: 33537
Ratings
- Top rated: 3.8
- Lowest rated: 1
- Summary of article content: Articles about ECMAScript – Wikipedia ECMAScript (or ES) is a JavaScript standard meant to ensure the interoperability of web pages … 6, June 2015, ECMAScript 2015 (ES2015), See 6th Edition – ECMAScript 2015 … …
- Most searched keywords: Whether you are looking for ECMAScript – Wikipedia ECMAScript (or ES) is a JavaScript standard meant to ensure the interoperability of web pages … 6, June 2015, ECMAScript 2015 (ES2015), See 6th Edition – ECMAScript 2015 …
- Table of Contents:
Contents
ECMAScript ECMA-262 and JavaScript[edit]
History[edit]
Features[edit]
Conformance[edit]
See also[edit]
References[edit]
External links[edit]
Navigation menu
![ECMAScript - Wikipedia](https://i0.wp.com/wpsites.net/wp-content/uploads/2014/06/icon-after-more-link.png)
See more articles in the same category here: https://chewathai27.com/to/blog.
ES6 (ES2015) là gì? Và tìm hiểu những tính năng mới.
17 Chia sẽ Facebook Twitter
ES6 là gì?
ECMAScript 6/ES6 là phiên bản mới nhất của bộ tiêu chuẩn ECMAScript – một bộ đặc tả tiêu chuẩn dành cho Javascript do Hiệp hội các nhà sản xuất máy tính Châu Âu (European Computer Manufacturers Association – ECMA) đề xuất. Phiên bảnECMAScript phổ biến ở thời điểm hiện tại (đầu 2015), và được hầu hết các trình duyệt hỗ trợ là ES5 và ES5.1 (ra mắt vào khoảng năm 2009 và 2011)
ES6 đã ra mắt vào giữa năm 2015 và được lấy tên chính thức là ES2015, với rất nhiều những tính năng mới lạ, và cần thiết đối với sự phát triển chóng mặt của Javascript trong những năm gần đây. Ngoài ra, phiên bản mới nhất của bộ đặc tả tiêu chuẩn này là ES7 cũng đang được phát triển, tuy chưa định ngày ra mắt chính thức nhưng cũng đã bắt đầu gây được sự chú ý của giới công nghệ với những tính năgn hấp dẫn như async function,observer,…
Trong phạm vi bài viết này, mình sẽ liệt kê ra một số chức năng nổi bật nhất. Và mình sẽ hạn chế dịch những tên khái niệm này ra tiếng Việt, để đảm bảo tính toàn vẹn của kiến thức (thực ra là vì dịch mấy từ thuật ngữ kiểu này ra tiếng Việt khó vô đối)
Các chức năng mới của ES6
Arrow
Arrow là một dạng viết tắt của các function sử dụng dấu => , tương tự như trong C#, Java 8,…
// Expression bodies var odds = evens.map(v => v + 1); var nums = evens.map((v, i) => v + i); var pairs = evens.map(v => ({even: v, odd: v + 1})); // Statement bodies nums.forEach(v => { if (v % 5 === 0) fives.push(v); }); // Lexical this var bob = { _name: “Bob”, _friends: [], printFriends() { this._friends.forEach(f => console.log(this._name + ” knows ” + f)); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 // Expression bodies var odds = evens . map ( v = > v + 1 ) ; var nums = evens . map ( ( v , i ) = > v + i ) ; var pairs = evens . map ( v = > ( { even : v , odd : v + 1 } ) ) ; // Statement bodies nums . forEach ( v = > { if ( v % 5 === 0 ) fives . push ( v ) ; } ) ; // Lexical this var bob = { _name : “Bob” , _friends : [ ] , printFriends ( ) { this . _friends . forEach ( f = > console . log ( this . _name + ” knows ” + f ) ) ; } }
Class
Đối với Javascript truyền thống, để sử khai báo và kế thừa các class, chúng ta phải thiết kế theo hướng sử dụng Prototype (prototype-based OO). Việc khai báo và kế thừa các class trong ES6 dễ hơn rất nhiều với cú pháp gần giống với Java và C++, ngoài ra, class trong ES6 cũng hỗ trợ kế thừa thông qua prototype, các static method, constructor,…
class SkinnedMesh extends THREE.Mesh { constructor(geometry, materials) { super(geometry, materials); this.idMatrix = SkinnedMesh.defaultMatrix(); this.bones = []; this.boneMatrices = []; //… } update(camera) { //… super.update(); } get boneCount() { return this.bones.length; } set matrixType(matrixType) { this.idMatrix = SkinnedMesh[matrixType](); } static defaultMatrix() { return new THREE.Matrix4(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class SkinnedMesh extends THREE . Mesh { constructor ( geometry , materials ) { super ( geometry , materials ) ; this . idMatrix = SkinnedMesh . defaultMatrix ( ) ; this . bones = [ ] ; this . boneMatrices = [ ] ; //… } update ( camera ) { //… super . update ( ) ; } get boneCount ( ) { return this . bones . length ; } set matrixType ( matrixType ) { this . idMatrix = SkinnedMesh [ matrixType ] ( ) ; } static defaultMatrix ( ) { return new THREE . Matrix4 ( ) ; } }
Xử lý chuỗi
Xử lý chuỗi trong ES6 đã trở nên dễ dàng và tiện dụng hơn rất nhiều, mang hơi hướng của các ngôn ngữ như Python, Perl,… đặc biệt, hỗ trợ chuỗi nhiều dòng, đây có lẽ là một cải tiến khiến rất nhiều người cảm thấy thích thú.
// Basic literal string creation `In JavaScript ‘n’ is a line-feed.` // Multiline strings `In JavaScript this is not legal.` // String interpolation var name = “Bob”, time = “today”; `Hello ${name}, how are you ${time}?` // Construct an HTTP request prefix is used to interpret the replacements and construction GET`http://foo.org/bar?a=${a}&b=${b} Content-Type: application/json X-Credentials: ${credentials} { “foo”: ${foo}, “bar”: ${bar}}`(myOnReadyStateChangeHandler); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // Basic literal string creation ` In JavaScript ‘n’ is a line – feed . ` // Multiline strings ` In JavaScript this is not legal . ` // String interpolation var name = “Bob” , time = “today” ; ` Hello $ { name } , how are you $ { time } ? ` // Construct an HTTP request prefix is used to interpret the replacements and construction GET ` http : //foo.org/bar?a=${a}&b=${b} Content – Type : application / json X – Credentials : $ { credentials } { “foo” : $ { foo } , “bar” : $ { bar } } ` ( myOnReadyStateChangeHandler ) ;
Giá trị default cho tham số
Ở phiên bản này, Javascript đã có thể sử dụng các giá trị mặc định cho tham số truyền vào các hàm như những ngôn ngữ lập trình khác như C++, C#.
function f(x, y=12) { // y = 12 nếu không truyền giá trị cho nó (hoặc truyền undefined) return x + y; } f(3) == 15 1 2 3 4 5 function f ( x , y = 12 ) { // y = 12 nếu không truyền giá trị cho nó (hoặc truyền undefined) return x + y ; } f ( 3 ) == 15
Truyền tham số không xác định số lượng
Việc này trước đây có thể thực hiện thông qua biến arguments có trong từng hàm, nhưng giờ đây chúng ta có thể sử dụng nó một cách linh hoạt hơn rất nhiều.
function f(x, …y) { // y là một mảng return x * y.length; } f(3, “hello”, true) == 6 1 2 3 4 5 function f ( x , . . . y ) { // y là một mảng return x * y . length ; } f ( 3 , “hello” , true ) == 6
Truyền tham số thông qua từng phần tử của mảng
Với kĩ thuật này, bạn có thể truyền một mảng hoặc một đối tượng vào một hàm, các phần tử của mảng/đối tượng này sẽ được tự động truyền vào thành các tham số của hàm đó.
function f(x, y, z) { return x + y + z; } // Pass each elem of array as argument f(…[1,2,3]) == 6 1 2 3 4 5 function f ( x , y , z ) { return x + y + z ; } // Pass each elem of array as argument f ( . . . [ 1 , 2 , 3 ] ) == 6
Từ khoá let và const
const , đúng như tên gọi của nó, là cách khai báo hằng số, một hằng số thì không thể thay đổi giá trị được.
const x = 10; x = 5; // Lỗi 1 2 const x = 10 ; x = 5 ; // Lỗi
let cũng là một dạng khai báo biến giống như var , tuy nhiên, biến được định nghĩa bằng từ khoá let có phạm vi truy cập khép kín trong khối lệnh chứa nó.
function testLet() { // a *không* truy cập được tại đây for( let a = 0; a < 5; a++ ) { // a chỉ truy cập được trong này }; // a *không* truy cập được tại đây }; function testVar() { // b truy cập *được* tại đây for( var b = 0; b < 5; b++ ) { // b truy cập được ở tất cả mọi nơi trong hàm testVar() }; // b truy cập *được* tại đây }; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 function testLet ( ) { // a *không* truy cập được tại đây for ( let a = 0 ; a < 5 ; a ++ ) { // a chỉ truy cập được trong này } ; // a *không* truy cập được tại đây } ; function testVar ( ) { // b truy cập *được* tại đây for ( var b = 0 ; b < 5 ; b ++ ) { // b truy cập được ở tất cả mọi nơi trong hàm testVar() } ; // b truy cập *được* tại đây } ; Modules Ở phiên bản này, Javascript đã chính thức hỗ trợ module. // lib/math.js export function sum(x, y) { return x + y; } export var pi = 3.141593; 1 2 3 4 5 // lib/math.js export function sum ( x , y ) { return x + y ; } export var pi = 3.141593 ; // app.js import * as math from "lib/math"; alert("2π = " + math.sum(math.pi, math.pi)); 1 2 3 // app.js import * as math from "lib/math" ; alert ( "2π = " + math . sum ( math . pi , math . pi ) ) ; // otherApp.js import {sum, pi} from "lib/math"; alert("2π = " + sum(pi, pi)); 1 2 3 // otherApp.js import { sum , pi } from "lib/math" ; alert ( "2π = " + sum ( pi , pi ) ) ; Module Loaders Module loaders hỗ trợ các kiểu load: – Dynamic loading – State isolation – Global namespace isolation – Compilation hooks – Nested virtualization Chúng ta có thể sử dụng loader mặc định ( System.import ) hoặc tự định nghĩa ra một loader mới. // Dynamic loading – ‘System’ is default loader System.import('lib/math').then(function(m) { alert("2π = " + m.sum(m.pi, m.pi)); }); // Create execution sandboxes – new Loaders var loader = new Loader({ global: fixup(window) // replace ‘console.log’ }); loader.eval("console.log('hello world!');"); // Directly manipulate module cache System.get('jquery'); System.set('jquery', Module({$: $})); // WARNING: not yet finalized 1 2 3 4 5 6 7 8 9 10 11 12 13 14 // Dynamic loading – ‘System’ is default loader System . import ( 'lib/math' ) . then ( function ( m ) { alert ( "2π = " + m . sum ( m . pi , m . pi ) ) ; } ) ; // Create execution sandboxes – new Loaders var loader = new Loader ( { global : fixup ( window ) // replace ‘console.log’ } ) ; loader . eval ( "console.log('hello world!');" ) ; // Directly manipulate module cache System . get ( 'jquery' ) ; System . set ( 'jquery' , Module ( { $ : $ } ) ) ; // WARNING: not yet finalized Map, Set, WeakMap, WeakSet ES6 còn giới thiệu thêm một số kiểu dữ liệu mới để hỗ trợ chúng ta thực hiện các thuật toán phức tạp hơn. // Sets var s = new Set(); s.add("hello").add("goodbye").add("hello"); s.size === 2; s.has("hello") === true; // Maps var m = new Map(); m.set("hello", 42); m.set(s, 34); m.get(s) == 34; // Weak Maps var wm = new WeakMap(); wm.set(s, { extra: 42 }); wm.size === undefined // Weak Sets var ws = new WeakSet(); ws.add({ data: 42 }); // Because the added object has no other references, it will not be held in the set 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // Sets var s = new Set ( ) ; s . add ( "hello" ) . add ( "goodbye" ) . add ( "hello" ) ; s . size === 2 ; s . has ( "hello" ) === true ; // Maps var m = new Map ( ) ; m . set ( "hello" , 42 ) ; m . set ( s , 34 ) ; m . get ( s ) == 34 ; // Weak Maps var wm = new WeakMap ( ) ; wm . set ( s , { extra : 42 } ) ; wm . size === undefined // Weak Sets var ws = new WeakSet ( ) ; ws . add ( { data : 42 } ) ; // Because the added object has no other references, it will not be held in the set Class kế thừa Trong ES6, các kiểu dữ liệu sẵn có như Array, Date, các DOM Elements có thể được kế thừa bởi các class mới. class MyArray extends Array { constructor(...args) { super(...args); } } var arr = new MyArray(); arr[1] = 12; arr.length == 2 1 2 3 4 5 6 7 class MyArray extends Array { constructor ( . . . args ) { super ( . . . args ) ; } } var arr = new MyArray ( ) ; arr [ 1 ] = 12 ; arr . length == 2 Promises Promises là một thư viện dùng cho lập trình bất đồng bộ (asynchronous programming), hiện nay, Promises đã được ứng dụng rộng rãi trên nhiều thư viện Javascript (ví dụ: AngularJS)
Learn ES2015 · Babel
es6features This document was originally taken from Luke Hoban’s excellent es6features repo. Go give it a star on GitHub!
REPL Be sure to try these features out in the online REPL.
Introduction
ECMAScript 2015 is an ECMAScript standard that was ratified in June 2015.
ES2015 is a significant update to the language, and the first major update to the language since ES5 was standardized in 2009. Implementation of these features in major JavaScript engines is underway now.
See the ES2015 standard for full specification of the ECMAScript 2015 language.
ECMAScript 2015 Features
Arrows and Lexical This
Arrows are a function shorthand using the => syntax. They are syntactically similar to the related feature in C#, Java 8 and CoffeeScript. They support both expression and statement bodies. Unlike functions, arrows share the same lexical this as their surrounding code. If an arrow is inside another function, it shares the “arguments” variable of its parent function.
var odds = evens.map( v => v + 1 ); var nums = evens.map( ( v, i ) => v + i); nums.forEach( v => { if (v % 5 === 0 ) fives.push(v); }); var bob = { _name : “Bob” , _friends : [], printFriends() { this ._friends.forEach( f => console .log( this ._name + ” knows ” + f)); } }; function square ( ) { let example = () => { let numbers = []; for ( let number of arguments ) { numbers.push(number * number); } return numbers; }; return example(); } square( 2 , 4 , 7.5 , 8 , 11.5 , 21 );
Classes
ES2015 classes are syntactic sugar over the prototype-based OO pattern. Having a single convenient declarative form makes class patterns easier to use, and encourages interoperability. Classes support prototype-based inheritance, super calls, instance and static methods and constructors.
class SkinnedMesh extends THREE . Mesh { constructor (geometry, materials) { super (geometry, materials); this .idMatrix = SkinnedMesh.defaultMatrix(); this .bones = []; this .boneMatrices = []; } update(camera) { super .update(); } static defaultMatrix() { return new THREE.Matrix4(); } }
Enhanced Object Literals
Object literals are extended to support setting the prototype at construction, shorthand for foo: foo assignments, defining methods and making super calls. Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences.
var obj = { __proto__ : theProtoObj, [ ‘__proto__’ ]: somethingElse, handler, toString() { return “d ” + super .toString(); }, [ “prop_” + ( ( ) => 42 )() ]: 42 };
The __proto__ property requires native support, and was deprecated in previous ECMAScript versions. Most engines now support the property, but some do not. Also, note that only web browsers are required to implement it, as it’s in Annex B. It is available in Node.
Template Strings
Template strings provide syntactic sugar for constructing strings. This is similar to string interpolation features in Perl, Python and more. Optionally, a tag can be added to allow the string construction to be customized, avoiding injection attacks or constructing higher level data structures from string contents.
`This is a pretty little template string.` `In ES5 this is not legal.` var name = “Bob” , time = “today” ; `Hello ${name} , how are you ${time} ?` String .raw `In ES5 ”
” is a line-feed.` GET `http://foo.org/bar?a= ${a} &b= ${b} Content-Type: application/json X-Credentials: ${credentials} { “foo”: ${foo} , “bar”: ${bar} }` (myOnReadyStateChangeHandler);
Destructuring
Destructuring allows binding using pattern matching, with support for matching arrays and objects. Destructuring is fail-soft, similar to standard object lookup foo[“bar”] , producing undefined values when not found.
var [a, ,b] = [ 1 , 2 , 3 ]; a === 1 ; b === 3 ; var { op : a, lhs : { op : b }, rhs : c } = getASTNode() var {op, lhs, rhs} = getASTNode() function g ( {name: x} ) { console .log(x); } g({ name : 5 }) var [a] = []; a === undefined ; var [a = 1 ] = []; a === 1 ; function r ( {x, y, w = 10 , h = 10 } ) { return x + y + w + h; } r({ x : 1 , y : 2 }) === 23
Default + Rest + Spread
Callee-evaluated default parameter values. Turn an array into consecutive arguments in a function call. Bind trailing parameters to an array. Rest replaces the need for arguments and addresses common cases more directly.
function f ( x, y= 12 ) { return x + y; } f( 3 ) == 15
function f ( x, …y ) { return x * y.length; } f( 3 , “hello” , true ) == 6
function f ( x, y, z ) { return x + y + z; } f(…[ 1 , 2 , 3 ]) == 6
Let + Const
Block-scoped binding constructs. let is the new var . const is single-assignment. Static restrictions prevent use before assignment.
function f ( ) { { let x; { const x = “sneaky” ; x = “foo” ; } x = “bar” ; let x = “inner” ; } }
Iterators + For..Of
Iterator objects enable custom iteration like CLR IEnumerable or Java Iterable. Generalize for..in to custom iterator-based iteration with for..of . Don’t require realizing an array, enabling lazy design patterns like LINQ.
let fibonacci = { [ Symbol .iterator]() { let pre = 0 , cur = 1 ; return { next() { [pre, cur] = [cur, pre + cur]; return { done : false , value : cur } } } } } for ( var n of fibonacci) { if (n > 1000 ) break ; console .log(n); }
Iteration is based on these duck-typed interfaces (using TypeScript type syntax for exposition only):
interface IteratorResult { done: boolean ; value: any ; } interface Iterator { next(): IteratorResult; } interface Iterable { [Symbol.iterator](): Iterator }
Support via polyfill In order to use Iterators you must include the Babel polyfill.
Generators
Generators simplify iterator-authoring using function* and yield . A function declared as function* returns a Generator instance. Generators are subtypes of iterators which include additional next and throw . These enable values to flow back into the generator, so yield is an expression form which returns a value (or throws).
Note: Can also be used to enable ‘await’-like async programming, see also ES7 await proposal.
var fibonacci = { [ Symbol .iterator]: function *( ) { var pre = 0 , cur = 1 ; for (;;) { var temp = pre; pre = cur; cur += temp; yield cur; } } } for ( var n of fibonacci) { if (n > 1000 ) break ; console .log(n); }
The generator interface is (using TypeScript type syntax for exposition only):
interface Generator extends Iterator { next(value?: any ): IteratorResult; throw (exception: any ); }
Support via polyfill In order to use Generators you must include the Babel polyfill.
Comprehensions
Removed in Babel 6.0
Unicode
Non-breaking additions to support full Unicode, including new unicode literal form in strings and new RegExp u mode to handle code points, as well as new APIs to process strings at the 21bit code points level. These additions support building global apps in JavaScript.
“𠮷” .length == 2 “𠮷” .match( /./u )[ 0 ].length == 2 “\u{20BB7}” == “𠮷” “𠮷” == “\uD842\uDFB7” “𠮷” .codePointAt( 0 ) == 0x20BB7 for ( var c of “𠮷” ) { console .log(c); }
Modules
Language-level support for modules for component definition. Codifies patterns from popular JavaScript module loaders (AMD, CommonJS). Runtime behaviour defined by a host-defined default loader. Implicitly async model – no code executes until requested modules are available and processed.
export function sum ( x, y ) { return x + y; } export var pi = 3.141593 ;
import * as math from “lib/math” ; console .log( “2π = ” + math.sum(math.pi, math.pi));
import {sum, pi} from “lib/math” ; console .log( “2π = ” + sum(pi, pi));
Some additional features include export default and export * :
export * from “lib/math” ; export var e = 2.71828182846 ; export default function ( x ) { return Math .exp(x); }
import exp, {pi, e} from “lib/mathplusplus” ; console .log( “e^π = ” + exp(pi));
Module Formatters Babel can transpile ES2015 Modules to several different formats including Common.js, AMD, System, and UMD. You can even create your own. For more details see the modules docs.
Module Loaders
Not part of ES2015 This is left as implementation-defined within the ECMAScript 2015 specification. The eventual standard will be in WHATWG’s Loader specification, but that is currently a work in progress. What is below is from a previous ES2015 draft.
Module loaders support:
Dynamic loading
State isolation
Global namespace isolation
Compilation hooks
Nested virtualization
The default module loader can be configured, and new loaders can be constructed to evaluate and load code in isolated or constrained contexts.
System.import( “lib/math” ).then( function ( m ) { alert( “2π = ” + m.sum(m.pi, m.pi)); }); var loader = new Loader({ global : fixup( window ) }); loader.eval( “console.log(\”hello world!\”);” ); System.get( “jquery” ); System.set( “jquery” , Module({ $ : $}));
Additional polyfill needed Since Babel defaults to using common.js modules, it does not include the polyfill for the module loader API. Get it here.
Using Module Loader In order to use this, you’ll need to tell Babel to use the system module formatter. Also be sure to check out System.js
Map + Set + WeakMap + WeakSet
Efficient data structures for common algorithms. WeakMaps provides leak-free object-key’d side tables.
var s = new Set (); s.add( “hello” ).add( “goodbye” ).add( “hello” ); s.size === 2 ; s.has( “hello” ) === true ; var m = new Map (); m.set( “hello” , 42 ); m.set(s, 34 ); m.get(s) == 34 ; var wm = new WeakMap (); wm.set(s, { extra : 42 }); wm.size === undefined var ws = new WeakSet (); ws.add({ data : 42 });
Support via polyfill In order to support Maps, Sets, WeakMaps, and WeakSets in all environments you must include the Babel polyfill.
Proxies
Proxies enable creation of objects with the full range of behaviors available to host objects. Can be used for interception, object virtualization, logging/profiling, etc.
var target = {}; var handler = { get : function ( receiver, name ) { return `Hello, ${name} !` ; } }; var p = new Proxy (target, handler); p.world === “Hello, world!” ;
var target = function ( ) { return “I am the target” ; }; var handler = { apply : function ( receiver, …args ) { return “I am the proxy” ; } }; var p = new Proxy (target, handler); p() === “I am the proxy” ;
There are traps available for all of the runtime-level meta-operations:
var handler = { get : …, set : …, has : …, deleteProperty : …, apply : …, construct : …, getOwnPropertyDescriptor : …, defineProperty : …, getPrototypeOf : …, setPrototypeOf : …, enumerate : …, ownKeys : …, preventExtensions : …, isExtensible :… }
Unsupported feature Due to the limitations of ES5, Proxies cannot be transpiled or polyfilled. See support in various JavaScript engines.
Symbols
Symbols enable access control for object state. Symbols allow properties to be keyed by either string (as in ES5) or symbol . Symbols are a new primitive type. Optional name parameter used in debugging – but is not part of identity. Symbols are unique (like gensym), but not private since they are exposed via reflection features like Object.getOwnPropertySymbols .
( function ( ) { var key = Symbol ( “key” ); function MyClass ( privateData ) { this [key] = privateData; } MyClass.prototype = { doStuff : function ( ) { … this[key] … } }; typeof key === “symbol” })(); var c = new MyClass( “hello” ) c[ “key” ] === undefined
Limited support via polyfill Limited support requires the Babel polyfill. Due to language limitations, some features can’t be transpiled or polyfilled. See core.js’s caveats section for more details.
Subclassable Built-ins
In ES2015, built-ins like Array , Date and DOM Element s can be subclassed.
class MyArray extends Array { constructor (…args) { super (…args); } } var arr = new MyArray(); arr[ 1 ] = 12 ; arr.length == 2
Partial support Built-in subclassability should be evaluated on a case-by-case basis as classes such as HTMLElement can be subclassed while many such as Date , Array and Error cannot be due to ES5 engine limitations.
Math + Number + String + Object APIs
Many new library additions, including core Math libraries, Array conversion helpers, and Object.assign for copying.
Number .EPSILON Number .isInteger( Infinity ) Number .isNaN( “NaN” ) Math .acosh( 3 ) Math .hypot( 3 , 4 ) Math .imul( Math .pow( 2 , 32 ) – 1 , Math .pow( 2 , 32 ) – 2 ) “abcde” .includes( “cd” ) “abc” .repeat( 3 ) Array .from( document .querySelectorAll( “*” )) Array .of( 1 , 2 , 3 ) [ 0 , 0 , 0 ].fill( 7 , 1 ) [ 1 , 2 , 3 ].findIndex( x => x == 2 ) [ “a” , “b” , “c” ].entries() [ “a” , “b” , “c” ].keys() [ “a” , “b” , “c” ].values() Object .assign(Point, { origin : new Point( 0 , 0 ) })
Limited support from polyfill Most of these APIs are supported by the Babel polyfill. However, certain features are omitted for various reasons (e.g. String.prototype.normalize needs a lot of additional code to support). You can find more polyfills here.
Binary and Octal Literals
Two new numeric literal forms are added for binary ( b ) and octal ( o ).
0b111110111 === 503 0o767 === 503
Only supports literal form Babel is only able to transform 0o767 and not Number(“0o767”) .
Promises
Promises are a library for asynchronous programming. Promises are a first class representation of a value that may be made available in the future. Promises are used in many existing JavaScript libraries.
function timeout ( duration = 0 ) { return new Promise ( ( resolve, reject ) => { setTimeout(resolve, duration); }) } var p = timeout( 1000 ).then( () => { return timeout( 2000 ); }).then( () => { throw new Error ( “hmm” ); }).catch( err => { return Promise .all([timeout( 100 ), timeout( 200 )]); })
Support via polyfill In order to support Promises you must include the Babel polyfill.
Reflect API
Full reflection API exposing the runtime-level meta-operations on objects. This is effectively the inverse of the Proxy API, and allows making calls corresponding to the same meta-operations as the proxy traps. Especially useful for implementing proxies.
var O = { a : 1 }; Object .defineProperty(O, ‘b’ , { value : 2 }); O[ Symbol ( ‘c’ )] = 3 ; Reflect .ownKeys(O); function C ( a, b ) { this .c = a + b; } var instance = Reflect .construct(C, [ 20 , 22 ]); instance.c;
Support via polyfill In order to use the Reflect API you must include the Babel polyfill.
Tail Calls
Calls in tail-position are guaranteed to not grow the stack unboundedly. Makes recursive algorithms safe in the face of unbounded inputs.
function factorial ( n, acc = 1 ) { “use strict” ; if (n <= 1 ) return acc; return factorial(n - 1 , n * acc); } factorial( 100000 )
Google Developers
ES2015 (formally ES6) is a fantastic step forward for the JavaScript language. It brings new features and sugaring for patterns that required significant boilerplate in ES5. This includes classes, arrow functions and modules. In this episode, we cover tools we use to take full advantage of ES2015 when building JavaScript web-apps.
Transpilation with Babel
Although JavaScript engines are making great progress in implementing ES2015 features natively, there is one gotcha. To use the complete set of features today, you will need to transpile your code back down to ES5 so it can be interpreted by current browsers. Thankfully, tools like Babel exist that make this process next to painless.
Using Babel in Your Build Process
Babel allows you to take JavaScript written using ES2015 features and transpiles it back to ES5 so that it can work in browsers that don’t support these features today. Adding Babel to your build process can be done like so.
var gulp = require(‘gulp’); var babel = require(‘gulp-babel’); gulp.task(‘default’, function () { return gulp.src(‘src/app.js’) .pipe(babel()) .pipe(gulp.dest(‘dist’)); });
The one feature Babel can’t transpile is Modules. Modules in ES6 allow you create classes and export / import classes between files. To transpile modules pass your JavaScript through Browserify, which will merge the files and then pass this through Babelify (a version of Babel which can handle the output from Browserify).
var babelify = require(‘babelify’); var source = require(‘vinyl-source-stream’); var browserify = require(‘browserify’); gulp.task(‘babelify’, function() { browserify({ entries: ‘./src.js’, debug: true }) .transform(babelify) .bundle() .pipe(source(‘bundle.js’)) .pipe(gulp.dest(‘./dist/js/’)); });
Multiple JavaScript Files
The above example requires you to define a specific file, which may become a bit of a burden, Matt does the following in Gulp to search and transpile files ending with .es6.js.
var config = { src: ‘src/scripts’, dest: ‘dist/scripts’ }; var es6FileGlob = ‘/**/*.es6.js’; var gulp = require(‘gulp’); var plugins = require(‘gulp-load-plugins’)(); var glob = require(‘glob’); var path = require(‘path’); var browserify = require(‘browserify’); var babelify = require(‘babelify’); var source = require(‘vinyl-source-stream’); // Takes an array of bundles to run through browserify and babelify function transpileES6Modules(browserifyFileEntries) { browserifyFileEntries.forEach(function(fileEntry) { var browserifyBundle = browserify({ entries: [fileEntry.srcPath] }) .transform(babelify); var finalStream = browserifyBundle.bundle() .on(‘log’, plugins.util.log.bind(plugins.util, ‘Browserify Log’)) .on(‘error’, plugins.util.log.bind(plugins.util, ‘Browserify Error’)) .pipe(source(fileEntry.outputFilename)); return finalStream.pipe(gulp.dest(fileEntry.dest)); }); } // This takes a source path and finds all files ending // with .es6.js and creates the bundles to run through browserify // and babelify function handleES6Scripts(srcPath) { var browserifyFileEntries = []; var es6Filepaths = glob.sync(srcPath + es6FileGlob); es6Filepaths.forEach(function(filepath) { var filename = path.basename(filepath); var directoryOfFile = path.dirname(filepath); var relativeDirectory = path.relative( srcPath, directoryOfFile); // Create an object and add to the browserify bundle array browserifyFileEntries.push({ srcPath: ‘./’ + filepath, outputFilename: filename, dest: path.join(config.dest, relativeDirectory) }); }); transpileES6Modules(browserifyFileEntries); } gulp.task(‘scripts:es6’, [‘scripts:lint’], function(cb) { handleES6Scripts(config.src); cb(); });
Linting and Style Checks
There are few options when linting your code for possible issues and style compliance.
JSHint and JSCS
JSHint and JSCS are the most common tools used for today’s JavaScript style-checking.
JSHint will highlight any possible issues in your code as well as call out any patterns generally regarded as bad practice.
JSCS will look at the style of your code, this includes things like ensuring just tabs or spaces are used and spaces are put in consistent places.
To use JSHint and JSCS on ES2015 code you need to add “esnext”: true to your .jshintrc and .jscsrc files
ESLint
ESLint is an alternative linter and style checker in one. This tool is picking up a lot of steam and has some nice features over JSHint such as being able to indicate environments your JavaScript is written for and setting the error / warning level for specific problems.
ESLint is fully customizable and provides custom linting rules where you’re in the driver’s seat of whether options can be switched off or toned down via its configuration files. In addition, if you’re using React, ESLint also works with JSX.
Setting up ESLint in your build process isn’t too hard either.
var gulp = require(‘gulp’), eslint = require(‘gulp-eslint’); gulp.task(‘lint’, function () { return gulp.src([‘js/**/*.js’]) // eslint() attaches the lint output to the eslint property // of the file object so it can be used by other modules. .pipe(eslint()) // eslint.format() outputs the lint results to the console. // Alternatively use eslint.formatEach() (see Docs). .pipe(eslint.format()) // To have the process exit with an error code (1) on // lint error, return the stream and pipe to failOnError last. .pipe(eslint.failOnError()); }); gulp.task(‘default’, [‘lint’], function () { // This will only run if the lint task is successful… });
The Babel team maintain babel-estlint, a tool that lets you lint any valid Babel code using ESLint. While ESLint supports custom parsers, some of the syntax supported by Babel isn’t directly supported by ESLint so it’s another option if you require even further flexibility. This can be setup by customizing the parser section of your .eslintrc file:
{ “parser”: “babel-eslint”, “rules”: { “strict”: 0 } }
Dan Abramov has a great write-up on setting up ESLint and babel-eslint in Lint Like It’s 2015. It also covers how to integrate SublimeLinter-eslint into your workflow for ES2015 linting support in Sublime Text.
Which should you use? Try them out and stick with what works best for you.
ES2015 Syntax Highlighting
You’ll of course want your ES2015 code to be correctly syntax highlighted. We enjoy using babel-sublime, which can be installed from Package Control. When setting up, we recommend making sure to set it as the default for any files you need highlighting to work against. This will of course include JS but may also cover JSX if using React.
Documenting ES2015
We’ve historically relied on JSDoc quite heavily for documenting our JavaScript code. Unfortunately, it has open issues for supporting ES2015 (due to be addressed in JSDoc 3), however there are a growing number of alternatives available while we wait for it to catch up. ESDoc is one such option and Jonathan Creamer has a recent write-up on it worth reading.
Authoring Gulp.js files with Babel
If you happen to be using Gulp for your build process, Gulpfiles can now be authored using any syntax supported by Babel. We do this over in Web Starter Kit and it’s relatively trivial to setup. Using a recent version of Gulp and the Gulp CLI, simply rename your gulpfile.js to gulpfile.babel.js and Gulp will interpret and transpile your ES2015 gulpfile using Babel automatically.
Favorite ES2015 Features
Modules
Modules are a way of exporting values, functions and classes from one file such that you can import them into another file.
export function exampleFunction() { console.log(‘I\’m an example. #TrueStory’); } import { exampleFunction } from ‘./example-function’; import BaseController from ‘./base-controller’; export default class ExampleController extends BaseController { constructor() { super(); exampleFunction(); } doSomething() { console.log(‘What should I do? Change the DOM? Print a dancing shark to the console?’); } }
This site has some great examples and explanations of Modules.
Template Strings
Template strings allow you to replace a port of a string with a variable.
// Simple string substitution var name = “Brendan”; console.log(‘Yo, ${name}!’); // => “Yo, Brendan!”
The nice thing with template strings is that the substitution is a JavaScript execution, meaning you can use functions or inline expressions.
var a = 10; var b = 10; console.log(‘a+b = ${a+b}.’); //=> a+b = 20. function fn() { return “I am a result. Rarr”; } console.log(‘foo ${fn()} bar’); //=> foo I am a result. Rarr bar.
You can learn more from this handy blog post by Addy.
Shorthand Object Literals
Object literals allow you to avoid having to define the key and value when creating an object, if the variable has the same name as the key you want the object to have.
Meaning this:
function createObject(name, data) { return { name: name, data: data }; }
Becomes this:
function createObject(name, data) { return { name, data }; }
Computed Property Names
This feature in ES2015 allows you to create property names dynamically on an object. The Mozilla docs is a great source of info and have this great example.
var a = { [“foo” + ++i]: i, [“foo” + ++i]: i, [“foo” + ++i]: i }; console.log(a.foo1); // 1 console.log(a.foo2); // 2 console.log(a.foo3); // 3
Fat Arrow Functions
Fat arrow functions allow you to write functions in shorthand where this:
button.addEventListener(‘click’, function(event) { console.log(‘The button has received a click’, event); });
Becomes this:
button.addEventListener(‘click’, (event) => { console.log(‘The button has received a click’, event); });
Apart from having a shorter syntax, one great feature of using fat arrow functions is that the scope of the object is the same the enclosing statement. What this means is that you don’t need to call .bind(this) on your function or create a var that = this.
There are plenty more examples over on MDN.
Addy has been busy keeping a list of ES2015 tools and if the tools above aren’t right for you, perhaps you are using Grunt instead of Gulp, then this may have an answer for you.
https://github.com/addyosmani/es6-tools
The above also includes links to additional Babel tooling that can help during unit testing and beyond.
Books to Read
There are two books you can check out for free online to learn more about ES2015. Understanding ECMAScript 6 written by Nicholas C. Zakas and Exploring ES6 written by Dr. Axel Rauschmayer.
Tower of Babel
If you’re interested in learning ES2015 features in your command-line, tower-of-babel offers a series of exercises that might be of interest. All of them walk through using Babel.
Other resources in case of interest:
So you have finished reading the es2015+ topic article, if you find this article useful, please share it. Thank you very much. See more: ECMAScript, Babel, Install babel, Babel/preset-es2015, Babel preset es2015 babel 7, Babel plugin, Babel/preset-env, Sự khác nhau giữa ES5 và ES6