ES6 General Introduction
-
Upload
thomas-johnston -
Category
Documents
-
view
92 -
download
1
Transcript of ES6 General Introduction
ES2015aka ES6
A lot of new features, a lot of syntactic sugar ...but they make writing JavaScript waaay easier
Cool Features We Should Use
let● Block scoped● Errors thrown if more than one let
by the same name in the same scope.
● Error is thrown if variable is called before value has been declared(TDZ).
const● Block scoped● Must be assigned a value when
declared and cannot be reassigned.
● Error thrown if more than one const or let have the same name in the same scope.
● Errors thrown if reassigned● Errors thrown if variable is called
before value has been declared(TDZ).
New vars in town
You should...// Use parens and curly brackets// avoid implicit returnsconst odds = evens.map((v) => { return v + 1;});
// This helps avoid nasty git diffsconst odds = evens.map(v => v + 1);const odds = evens.map((v) => { let x = v + 1; return x;});
Arrow functions
You can... // no parens or curly brackets// implicit return for one linerconst odds = evens.map(v => v + 1);
ES6// No need for bind/call/applyfunction iterate() { this.array = [1, 2, 3]; this.array.forEach((i) => { this.array; });}
Lexical this for arrow functions
Transpilation// Caches the this referencefunction iterate() { var _this = this; this.array = [1, 2, 3]; this.array.forEach(function(i) { _this.array; });}
● You can create plain old strings
● No \ or concatenation for multiline strings
● Whitespace is preserved● Interpolate variables
and expressions● Compute in code as well
// Basic literal string creation`My little string :]`
// Multiline strings`In ES5 this is not legal.`
// String interpolationconst name = ‘Slim Shady’;`My name is what My name is who My name is chka-chka ${name}`
// Raw representationconst x = 1;String.raw`x is ${x}`;// ‘x is 1’
Template strings
Template Strings as function argumentslet a = 5;let b = 10;
function tag(strings, ...values) { strings[0]; // ‘Hello ‘ strings[1]; // ‘ world ‘ values[0]; // 5 values[1]; // 10
return ‘Bazinga!’;}
tag`Hello ${a} world ${b}`; // ‘Bazinga!’
Changing function arguments
Defaults
Specify defaults in the function signaturefunction f(x=1) {
Replaces x = x || 1;
Rest
Name trailing argsfunction f(x, ...y) {
Replaces need to use implicit arguments variable
Spread
Invoke functionsfunction f(x, y, z) {
...
f(...[1,2,3])
Replaces some needs for apply
● Allows binding with pattern matching
● Support for Array and Object
● Allows defaults and some error handling
● Items that aren’t present are assigned undefined
getData();// returns {a: 1, b: 2}
let {a, b} = getData();a === 1; // trueb === 2; // true
// In function parametersfunction g({key: x}) { return x;}g({key: 1}); // 1
Destructuring
<aside>Allows you to change function usage without refactoring invocations</aside>
Destructuring an Array
Pull what you need
let [a, ,b] = [1,2,3];a === 1; // trueb === 3; // true
Error Handling
let [a] = [];a === undefined; // true
Defaults
let [a = 1] = [];a === 1; // omg so true
Modules with import and export
import// import *import * as stuff from ‘/stuff’
// import with destructuringimport {a, b} from ‘/stuff’
export// export functionsexport function sum(x, y) {...
// export variablesexport var x = 1;
// export defaultexport default function(x) {
● Setting __proto__ directly○ Can still use the
name● Shorthanding
assignments of the same name
● Method shorthand● Calls to super● Dynamic property names
let keyPostfix = 1;let handler = someHandler;
let obj = { __proto__: theProtoObj, handler, // handler: handler toString() { return super.toString(); }, [ 'b' + keyPostfix ]: 0};// obj['b' + keyPostfix] = 0
Object Literals
Cool Features We Should Use Sparingly
Using classes
Supports ctors & static
class Person { constructor(x) { this.name = x; } getName() { return this.name; } static sayMyName(x) { return `${x.name}`; }}
Extends
class Bob extends Person { constructor() { super(‘Bob’); } getName() { return super.getName(); }}
Extend OTB Objects
No more overriding base classes or writing delegators:
class A extends Array {...
class D extends Date {...
class E extends Element {...
...but we should use the Ember.Object model in most cases
Number and Math APIsNumber.EPSILON;Number.isInteger(Infinity); // falseNumber.isNaN('NaN'); // false
Math.acosh(3); // 1.762747174039086Math.hypot(3, 4); // 5Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2); // 2
String, Array and Object APIs'abcde'.includes('cd'); // true'abc'.repeat(3); // 'abcabcabc'
Array.from(document.querySelectorAll('*')); // Returns a real ArrayArray.of(1, 2, 3); // Like new Array(...), but no special one-arg behavior[0, 0, 0].fill(7, 1); // [0,7,7][1,2,3].findIndex(x => x == 2); // 1['a', 'b', 'c'].entries(); // iterator [0, 'a'], [1,'b'], [2,'c']['a', 'b', 'c'].keys(); // iterator 0, 1, 2['a', 'b', 'c'].values(); // iterator 'a', 'b', 'c'
Object.assign(Point, { origin: new Point(0,0) });
Some other stuff...// Unicode‘\u{20BB7}’ == ‘ ’ == ‘\uD842\uDFB7’;
// Binary and Octal literals0b111110111 === 503 // true0o767 === 503 // too true
Cool Features We Shouldn’t Use
You should explore them more but here’s why:
Iterators, generators
Custom Module Loaders
Map, Set, WeakMap, WeakSet
Proxies
Symbol
Promises
Reflect
Tail Calls
Requires polyfill, weirdness with immutability
Better off using something already made
Requires polyfill
Cannot be transpiled or polyfilled
Limited Support
Requires loading a separate runtime
Requires polyfill
Partially supported, can be a memory hog(until browser support is there)
...they are worth keeping an eye on though
Resources
Learn ES2015/ES6
AirBNB coding standards
Try it out
Destructuring assignment on MDN