JS - ES6 Flashcards

1
Q

Arrow functions (1)

A
/* 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

~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Modules

A

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
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Classes (1)

A

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.');
  }
}

~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Classes (2)

A

```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) {

~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Block-Scoped Constructs Let and Const

A

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
}

~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Promises

A

```javascript
var wait1000 = () => new Promise((resolve, reject) => {
setTimeout(resolve, 1000)
})

wait1000()
    .then(function() {
        console.log('Yay!')
        return wait1000()
    })
    .then(function() {
        console.log('Wheeyee!')
    });

~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Arrow functions (2)

A

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()
})
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Multi-line Strings

A

```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
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Template literals

A

```javascript
var name = Your name is ${first} ${last}.
var url = http://localhost:3000/api/messages/${id}
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Default parameters

A

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’) {

}
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Constants

A

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
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Destructuring

A

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);
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Spread operator

A

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]
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Data structure - Set

A

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’]);
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Pro-tip - Merge two sets

A

```javascript
let set1 = new Set([‘dog’, ‘horse’]);
let set2 = new Set([‘cat’, ‘owl’]);
let set3 = new Set([…set1, …set2]);
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Pro-tip - Use a variable value as object key

A

```javascript
const somevar1 = ‘name’
const somevar2 = {
[somevar1]: ‘Bob’
}
~~~

17
Q

Spread operator vs Rest parameter

A

When using spread, you are expanding a single variable into more:

```javascript
var abc = [‘a’, ‘b’, ‘c’];
var def = [‘d’, ‘e’, ‘f’];
var alpha = [ …abc, …def ];
// alpha == [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’];
~~~

When using rest arguments, you are collapsing all remaining arguments of a function into one array:

```javascript
function sum( first, …others ) {
for ( var i = 0; i