ES6 Flashcards

1
Q

What three new methods does ES6 introduce for identifying whether a given string contains a substring?

A

includes(), startsWith() and endsWith() // These won’t work with regular expressions

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

What are tagged template literals?

A

Functions that receive pieces of a template literal as arguments which you can manipulate and return as html.

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

How can you easily clone an array using rest parameters?

A

let […clonedArray] = myArray;

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

For function doSomething () { … } how can you get the name “doSomething” from within or without the function?

A

doSomething.name

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

How can you make sure a function was called with the ‘new’ keyword?

A

if (typeof new.target !== ‘undefined’) { // the function was called using new. This is better than checking if this instanceof Person, for example.

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

Make an arrow function into an immediately invoked function: (value) => {
doSomething(value)
return value;
}

A

Wrap in parens: ((value) => {…})(‘Something’)

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

What’s a tail call?

A

When a function is called as the last statement in another function the compiler has trouble optimizing.

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

How can you optimize for tail calls when they are necessary?

A

Don’t require access to variables in the current stack frame (the function can’t be a closure); the function making the tail call has no more work todo after the tail call returns; the result of the tail call is returned as the function value.

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

How does Object.is() work?

A

Accepts 2 arguments and returns true if they are the same type and value. Object.is(NaN, NaN); // true

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

How does Object.assign() work?

A

Object.assign(receiver, supplier); It takes two objects and adds the properties/values from supplier to receiver. It modifies receiver.

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

What does the super() method do? How does it work?

A

‘super’ is a pointer to the current object’s prototype. It’s like saying Object.getPrototypeOf(this). It must be inside a ‘concise’ method to work.

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

What is a concise method of an object literal?

A

Instead of var person = { getAge: function() { … } we can say var person = { getAge() { … } ,

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

Why send destructured parameters to a function? What does this mean/do?

A
It helps clarify what the function requires: 
function myFunction (name, value, { url, filename, size }  = { } ) { ... } // Note: the parameters are required if you don't set a default
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Add newItem onto the end of array someArray using spread operator

A

[ …someArray, newItem ]

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

How to make this work:

var a, b;
{a, b} = {a: 1, b: 2};

A

Move the destructing into parenthesis:
var a, b;
({a, b} = {a: 1, b: 2});

or use let/const/var

var {a, b} = {a: 1, b: 2};

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

Using destructing a variable can be assigned a default, in the case that the value unpacked from the object is undefined. How to do this?

A

var {a = 10, b = 5} = {a: 3};

console. log(a); // 3
console. log(b); // 5

17
Q

var {a:aa = 10, b:bb = 5} = {a: 3};

what does this mean?

A

It’s an assigning to new variables names and providing default values

console. log(aa); // 3
console. log(bb); // 5

18
Q

How to unpack User in whois parameter?

function whois(???) {
  console.log(displayName + ' is ' + name);
}
var user = { 
  id: 42, 
  displayName: 'jdoe',
  fullName: { 
      firstName: 'John',
      lastName: 'Doe'
  }
};
A

The args should be
{displayName, fullName: {firstName: name}}

i.e. function whois({displayName, fullName: {firstName: name}}) {
console.log(displayName + ‘ is ‘ + name);
}

19
Q

Give an example of computed object property names in destructuring

A
let key = 'z';
let {[key]: foo} = {z: 'bar'};

console.log(foo); // “bar”

20
Q

Is it possible to use Rest in Object Destructuring

A

For arrays:
var [a, …b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // [2, 3]

The Rest/Spread Properties for ECMAScript proposal (stage 3) adds the rest syntax to destructuring. Rest properties collect the remaining own enumerable property keys that are not already picked off by the destructuring pattern.

let {a, b, …rest} = {a: 10, b: 20, c: 30, d: 40}
a; // 10
b; // 20
rest; // { c: 30, d: 40 }

21
Q

What will be printed?

function print(a, b, ...c) {
    console.log(a); 
    console.log(b); 
    console.log(c); 
}

print(…[3], …[1, 2, 12]);

A

3
1
[ 2, 12 ]

22
Q
For the following function
function print(a, b, ...c) {
    console.log(a); 
    console.log(b); 
    console.log(c); 
}
what would be printed in case 
x = [0, 5]; print([12, ...x, 10]);
and
x = [0, 5]; print(...[12, ...x, 10]);
?
A

[ 12, 0, 5, 10 ]
undefined
[]

vs

12
0
[ 5, 10 ]

23
Q

What’d be in console?

x = [0, 5];

console. log(“Array: ${x[0]}, ${x}”);
console. log(‘Array: ${x[0]}, ${x}’);
console. log(Array: ${x[0]}, ${x});

A

Array: ${x[0]}, ${x}
Array: ${x[0]}, ${x}
Array: 0, 0,5

Template literals require ‘ticks’ - ` symbol

24
Q

What’d be printed for custom tag like this:

console.log(lowerTag ${1} + ${2} EQUALS ${1+2});

let lowerTag = function (strings, ...values) {
    let result = "";
    strings.forEach((s, i) => {
        result += s;
        if(i < values.length)
            result += values[i];
    });
return result.toLowerCase(); }
A

1 + 2 equals 3

25
Q

В чем отличия for .. in и for .. of ?
Что выведет код:
let arr = [ 3, 5, 7 ];
arr.foo = “hello”;

for (let i in arr) {
console.log(i); // выведет ???
}

for (let i of arr) {
console.log(i); // выведет ???
}

A

Следующий пример показывает различия циклов for…of и for…in. В то время как for…in обходит имена свойств, for…of выполняет обход значений свойств:

let arr = [ 3, 5, 7 ];
arr.foo = "hello";

for (let i in arr) {
console.log(i); // выведет “0”, “1”, “2”, “foo”
}

for (let i of arr) {
console.log(i); // выведет “3”, “5”, “7”
}

26
Q

Что такое генератор?

A
То же что Enumerator в c#
var gen = function*()
{
    yield 100;
    yield 200;
    yield 300;
}
27
Q

Как итерироваться по массиву без for of?

A
arr.forEach(function callback(currentValue, index, array) {
    //your iterator
}[, thisArg]);

currentValue
Текущий обрабатываемый элемент в массиве.

index Необязательный
Индекс текущего обрабатываемого элемента в массиве.
array Необязательный
Массив, по которому осуществляется проход.

thisArg
Необязательный параметр. Значение, используемое в качестве this при вызове функции callback.

Примечание: Не существует способа остановить или прервать цикл forEach() кроме как выбрасыванием исключения. Если это требуется, метод forEach() неправильный выбор. Используйте обычные циклы. Если нужно протестировать элементы массива на условие и нужно вернуть булевое значение, вы должны воспользоваться методами Array.prototype.every() или Array.prototype.some().

28
Q

Простой способ использовать forEach на множестве document.querySelectorAll(‘a’)

A
[].forEach.call( document.querySelectorAll('a'), function(el) {
   // whatever with the current node
});
29
Q

What are three roles (patterns) of generators?

A

Generators can play three roles:

Iterators (data producers): Each yield can return a value via next(), which means that generators can produce sequences of values via loops and recursion. Due to generator objects implementing the interface Iterable (which is explained in the chapter on iteration), these sequences can be processed by any ECMAScript 6 construct that supports iterables. Two examples are: for-of loops and the spread operator (…).
Observers (data consumers): yield can also receive a value from next() (via a parameter). That means that generators become data consumers that pause until a new value is pushed into them via next().
Coroutines (data producers and consumers): Given that generators are pausable and can be both data producers and data consumers, not much work is needed to turn them into coroutines (cooperatively multitasked tasks).

30
Q

What ES6 language constructs dot support generators?

A

First, the for-of loop:

for (const x of genFunc()) {
    console.log(x);
}
// Output:
// a
// b
Second, the spread operator (...), which turns iterated sequences into elements of an array (consult the chapter on parameter handling for more information on this operator):
const arr = [...genFunc()]; // ['a', 'b']
Third, destructuring:
> const [x, y] = genFunc();
> x
'a'
> y
'b'
31
Q

How many “results” genObj.next() can produce?

A

3:

  • For an item x in an iteration sequence, it returns { value: x, done: false }
  • For the end of an iteration sequence with a return value z, it returns { value: z, done: true }
  • For an exception that leaves the generator body, it throws that exception.
32
Q

How to make recursion call of a generator?

A
function* bar(i) {
    if(i > 1)
        return '---';
    yield 'x';
    yield* bar(++i);
    yield 'y';
}

for (let i of bar(0)) {
console.log(i);
}

33
Q
Что выведет код
function* bar(i) {
    if(i > 1)
        return '---';
    yield 'x';
    yield* bar(++i);
    yield 'y';
}

for (let i of bar(0)) {
console.log(i);
}

A

x
x
y
y

34
Q

Create a class with binary tree and a function to iterate through it

A
class BinaryTree {
    constructor(value, left=null, right=null) {
        this.value = value;
        this.left = left;
        this.right = right;
    }
    /** Prefix iteration */
    * [Symbol.iterator]() {
        yield this.value;
        if (this.left) {
            yield* this.left;
            // Short for: yield* this.left[Symbol.iterator]()
        }
        if (this.right) {
            yield* this.right;
        }
    }
}
const tree = new BinaryTree('a',
    new BinaryTree('b',
        new BinaryTree('c'),
        new BinaryTree('d')),
    new BinaryTree('e'));

for (const x of tree) {
console.log(x);
}

35
Q

Как добавить в объект “итерацию по умолчанию”?

A

The Symbol.iterator well-known symbol specifies the default iterator for an object. Used by for…of.

const iterable1 = new Object();

iterable1[Symbol.iterator] = function* () {
  yield 1;
  yield 2;
  yield 3;
};

console.log([…iterable1]);