JS - ES6 Flashcards
Arrow functions (1)
/* This doesn't work ================================================== */
var person = { first: 'Doug', actions: ['bike', 'hike', 'ski', 'surf'], printActions: function() { this.actions.forEach(function(action) { var str = this.first + ' likes to ' + action; console.log(str); }) } }; person.printActions(); // undefined likes to bike // undefined likes to hike // undefined likes to ski // undefined likes to surf
/* This works (ES5) ================================================== */
var person = { first: 'Doug', actions: ['bike', 'hike', 'ski', 'surf'], printActions: function() { var that = this; this.actions.forEach(function(action) { var str = that.first + ' likes to ' + action; console.log(str); }) } }; person.printActions(); // Doug likes to bike // Doug likes to hike // Doug likes to ski // Doug likes to surf
/* This works (ES5) ================================================== */
var person = { first: 'Doug', actions: ['bike', 'hike', 'ski', 'surf'], printActions: function() { this.actions.forEach(function(action) { var str = this.first + ' likes to ' + action; console.log(str); }.bind(this)) } }; person.printActions(); // Doug likes to bike // Doug likes to hike // Doug likes to ski // Doug likes to surf
/* This works (ES6) ================================================== */
var person = { first: 'Doug', actions: ['bike', 'hike', 'ski', 'surf'], printActions() { this.actions.forEach(action => { var str = this.first + ' likes to ' + action; console.log(str); }) } }; person.printActions(); // Doug likes to bike // Doug likes to hike // Doug likes to ski // Doug likes to surf
~~~
Modules
In ES6, we would use export and import. For example, this is our library in the ES6 module.js file:
```javascript
export var port = 3000
export function getAccounts(url) {
…
}
~~~
In the importer ES6 file main.js, we use import {name} from ‘my-module’ syntax. For example,
```javascript
import {port, getAccounts} from ‘module’
console.log(port) // 3000
~~~
Classes (1)
JavaScript classes are introduced in ECMAScript 6 and are syntactical sugar over JavaScript’s existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance
```javascript
class Cat {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ‘ makes a noise.’);
}
}
class Lion extends Cat { speak() { super.speak(); console.log(this.name + ' roars.'); } }
~~~
Classes (2)
```javascript
class baseModel {
constructor(options = {}, data = []) { // class constructor
this.name = ‘Base’
this.url = ‘http://azat.co/api’
this.data = data
this.options = options
}
getName() { // class method console.log(`Class name: ${this.name}`) } }
```
```javascript
class AccountModel extends baseModel {
constructor(options, data) {
…
~~~
Block-Scoped Constructs Let and Const
The let statement declares a block scope local variable, optionally initializing it to a value.
```javascript
function varTest() {
var x = 1;
if (true) {
var x = 2; // same variable!
console.log(x); // 2
}
console.log(x); // 2
}
function letTest() { let x = 1; if (true) { let x = 2; // different variable console.log(x); // 2 } console.log(x); // 1 }
~~~
Promises
```javascript
var wait1000 = () => new Promise((resolve, reject) => {
setTimeout(resolve, 1000)
})
wait1000() .then(function() { console.log('Yay!') return wait1000() }) .then(function() { console.log('Wheeyee!') });
~~~
Arrow functions (2)
Using arrows functions in ES6 allows us to stop using that = this or self = this or that = this or .bind(this)
```javascript
// ES5
var _this = this
$(‘.btn’).click(function(event){
_this.sendData()
})
// ES6
$(‘.btn’).click((event) =>{
this.sendData()
})
~~~
Multi-line Strings
```javascript
// ES5
var roadPoem = ‘Then took the other, as just as fair,\n\t’
+ ‘And having perhaps the better claim\n\t’
+ ‘Because it was grassy and wanted wear,\n\t’
+ ‘Though as for that the passing there\n\t’
+ ‘Had worn them really about the same,\n\t’
// ES6
var roadPoem = Then took the other, as just as fair,
And having perhaps the better claim
Because it was grassy and wanted wear,
Though as for that the passing there
Had worn them really about the same
~~~
Template literals
```javascript
var name = Your name is ${first} ${last}.
var url = http://localhost:3000/api/messages/${id}
~~~
Default parameters
They were okay until the value was 0 and because 0 is falsy in JavaScript it would default to the hard-coded value instead of becoming the value itself. Of course, who needs 0 as a value (#sarcasmfont), so we just ignored this flaw and used the logic OR anyway… No more! In ES6, we can put the default values right in the signature of the functions
```javascript
// ES5
var link = function (height, color, url) {
var height = height || 50
var color = color || ‘red’
var url = url || ‘http://azat.co’
…
}
// ES6
var link = function(height = 50, color = ‘red’, url = ‘http://azat.co’) {
…
}
~~~
Constants
Support for constants (also known as “immutable variables”), i.e., variables which cannot be re-assigned new content. Notice: this only makes the variable itself immutable, not its assigned content (for instance, in case the content is an object, this means the object itself can still be altered).
```javascript
const PI = 3.141593
~~~
Destructuring
The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects into distinct variables
```javascript
var animal = {
species: ‘dog’,
weight: 23,
sound: ‘woof’
};
var { species, sound } = animal;
console.log(species, ‘says’, sound);
~~~
Spread operator
Spreading of elements of an iterable collection (like an array or even a string) into both literal elements and individual function parameters.
```javascript
var arr1 = [1,2];
var arr2 = […arr1, 3, 4]; // [1, 2, 3, 4]
~~~
Data structure - Set
The Set object lets you store unique values of any type, whether primitive values or object references
```javascript
// Creation
let s = new Set()
// Store only unique values
s.add(“hello”).add(“goodbye”).add(“hello”)
s.size === 2
// Check if a value exists
s.has(“hello”) === true
// Loop
for (let key of s.values())
console.log(key)
~~~
or
```javascript
let s = new Set([‘hello’, ‘goodbye’]);
~~~
Pro-tip - Merge two sets
```javascript
let set1 = new Set([‘dog’, ‘horse’]);
let set2 = new Set([‘cat’, ‘owl’]);
let set3 = new Set([…set1, …set2]);
~~~