ES6 Flashcards

Master the language

1
Q

Arrow functions props

A
  1. Cannot be used as constructors;
  2. They have no “this”;
  3. They have no “super”;
  4. They have no new.target;
  5. They have no prototype;
  6. They have no “arguments” object;
  7. They have no duplicate named parameters.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What do arrow functions of 1 parameter return?

A

The expression to the right

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

In what do you have to wrap an arrow function that returns an object literal?

A
In ( );
Example: let myResult = id => ({id: id, name: "RSE});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Can you change “this” by using bind(), call() or apply() in arrow functions?

A

No

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

Can you access in arrow function the “arguments” from a function that contains it?

A
Yes. 
Ex: 
      function containingFunction(){
           return () => argument[0];
      }
     var myFunction = containingFunction(5);
    console.log(myFunction()); // 5
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Can you use bind(), call() and apply() on arrow functions?

A

yes

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

What is the difference between the new string methods includes() and startsWith() on one side, and endsWidth() on the other side? Clue: something related to 2nd parameter

A

endsWidth() starts the match from the length of the string minus the 2nd argument, whereas startsWith() and includes() start the match from that index given by the 2nd arg

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q
Having a function:
function makeRequest(a,b=3,c){
         return a+b+c;
}

what is the function returning if I do makeRequest(2,null,5)?

a. null;
b. 10;
c. 7;
d. 192

A

c) because if I use null for a default parameter, null is considered valid and that value will NOT be used.

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

How is the behaviour of “arguments” different in ES5 vs ES6?

A

In ES5 non-strict mode, “arguments” will “follow” a function named arguments;
In ES5 strict mode, “arguments” does not reflect the changes of named parameters;
In ES6, “arguments” is detached from named arguments, irrespective of strict or non-strict node.

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

If I have a function:

function mixArgs(first,second=”b”){ console.log(arguments)}

  1. What is the value of arguments[1] if I call the function as in mixArgs(100)?
  2. Also what is the function call f=mixArgs(100) going to print?
A
  1. undefined, because arguments[1] = undefined

2. Arguments [100, calee(…), Symbol(Symbol.iterator):f]

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

Why is possible and correct to write:

function getValue(value){
         return value+5};
function add(first, second = getValue(first)){
        return first + second;}
A

Because in ES6 it is allowed to use a previous parameter as a default for a second parameter.
(not allowed the other way around though)

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

In loops, in order to avoid creating closures, what is the recommended concept to use instead of plain functions?

A

IIFEs;

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

What is Javascript doing when it looks through an upcoming block and finds a variable declaration?
What is the difference behaviour between “var” compared to “let” and “const” declarations in this case?

A

The declaration with “var” is hoisted at the beginning of the current scope;
The “const” and “let” declarations are placed in the TDZ, where they will stay until that execution flow passes the declaration point.
“let” and “const” are NOT hoisted!!

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

Which ones of the two typeof instructions below will return “undefined” and which one will throw an error?

console.log(typeof(a));
let f3 = function() {
       console.log(typeof(a));
       let a = 3;
}
A

The 2nd typeof will throw an error, because a is in the TDZ at the moment of the call of that typeof, whereas the first typeof will just return “undefined”, because the variable a at that scope is not in the TDZ (is no blocked by a “let” or a “const” declaration at that scope level)

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

When is the parameter initialization happening for a function?

a. When the function is declared;
b. When the function is called;

A

When the function is called

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

Function parameters and function body have:

a. the same scope or a different scope;
b. the same TDZ or a different TDZ.

A

Both are different&raquo_space;> a function’s default params cannot access any variables declared inside the function body

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

What is the “pick()” function in the “Underscore.js” library doing?

A

Returns a copy of a given object with some specific subset of the original properties.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q
What is the function presented below going to return if called as:
let f = function(x,...y){
        console.log(arguments.length)}
let a = 100;
let b = [200, 300];
f(a,b);
A

3

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

What is the console.log() presented below going to print?

let f = function(x,...y){
        x+y[0]}
let a = 100;
let b = [200, 300];
console.log(f.length);
A

1, and not 2 or 3, because rest parameters DO NOT affect the function’s length property

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

What are the rest parameters restrictions?

A
  1. There can only be one rest parameter;
  2. The rest parameter has to be the last of the function parameters;
  3. The rest parameters cannot be used in an object literal setter, like:
let object = {
      // Syntax error
     set name(...value){
                // do something
     }
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How are the rest parameters influencing the “arguments” object for a function?

A

There is no influence, “arguments” will reflect 3 if f(a,…b) and a=100,b=200,c=300.

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

What is the spread operator used usually to replace?

A

The apply() method as it is far easier to do
Math.max(…values, 0)) where
values=[100,200];

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

What is the restriction on the object literal setters?

A

They are restricted to a single argument

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

What are the differences between spread parameters and rest arguments?

A
1. Spread parameters are used when you call the function:
        var abc = ['a', 'b', 'c'];
        var def = ['d', 'e', 'f'];
        var alpha = [ ...abc, ...def];
Rest arguments are used when you define a function:
         function sum(first, ...others){.........};
  1. Rest argument has to be only one, whereas the spread parameters can be as many as you like;
  2. The rest argument has to come on the last position, whereas the spread arguments can have any position.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is the console.log() going to print?

var doSomething = function doSomethingElse(){ }
console.log(doSomething.name);
A

doSomethingElse

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

What is the console.log() instructions below going to print?

var person = {
      get firstName () {
             return "Nicholas"
      },
     sayName: function(){
             console.log(this.name);
      }
}
1.  console.log(person.sayName.name);
2. console.log(person.firstName.name);
A
  1. “sayName”

2. “get firstName”

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

Why is it not possible to use the “name” property of a function to get access to it?

A

because the “name” property is only meant to be informative (in the debugging process, for ex.)

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

What is the console.log() instruction going to be print?

var doSomething = function(){ };

console.log(doSomething.bind().name);

A

“bound doSomething” as functions created with “bind” will prefix their name with “bound”.

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

What is the console.log() instruction going to be print?

console.log((new Function()).name);

A

“anonymous” because functions created using the Function constructor use the name “anonymous”

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

What is the role of the new.target metaproperty in ES6?

A
Is to solve the problem of naming functions created with "new". Inside a function declaration, new.target will filled with something (the target of the "new" operator), so I can use it to detect if a function has been called with "new" or not:
function Person(name){
       if (typeof new.target !== "undefined"){
                 this.name = name;
       } else {
                throw new Error("You must use new with person");
       }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Can you call an arrow function as a constructor?

A

No, is not allowed in ES6

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

Having the following code:

"use strict";
if(true) {
      console.log(typeof doSomething);
      function doSomething(){ }
      doSomething();
}
console.log(typeof doSomething);

What are the two console.log() instructions going to print?

A
  1. “function” because the function declaration within the if block will be hoisted to the top of the if block
  2. “undefined” because doSomething() is inexistent outside the block within it has been defined.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

Having the following code:

“use strict”;

if (true) {
    console.log(typeof doSomething);
    let doSomething = function() { };
    doSomething();
}
console.log(typeof doSomething);

What are the two console.log() instructions going to print?

A
  1. throws an error because “let” expressions do not hoist in strict mode;
  2. “undefined”;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What is the difference between block-level functions’ behaviour in “strict” mode compared to “non-strict” mode?

A

In “strict” mode, the block-level functions are being hoisted at the top of the containing block, whereas in “non-strict” mode they are being hoisted all the way to the containing function or the global environment.

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

Having the following code:

if(true) {
      console.log(typeof doSomething);
      function doSomething(){ }
      doSomething();
}
console.log(typeof doSomething);

What are the two console.log() instructions going to print?

A
  1. “function” because the function declaration within the if block in non-strict mode will be hoisted to the global scope or the containing function (in this case is global scope)
  2. “function” because doSomething() is hoisted in this case to the global scope
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

How is the “this” value going to be defined in an arrow function?

A

By the closest non-arrow function that surrounds my arrow function, or by the global scope.

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

How do you create an IIFE out of an arrow function?

A

By surrounding it in ( )

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

What is the difference between concise methods and non-concise methods in respect with “super”?

A

The concise methods can access “super”, whereas the non-concise methods cannot;

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

What is the result of this operation? NaN === NaN

A

false

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

What is Object.assign() used for? How does it work? What does it return?

A

For mixins. It accepts a receiver and lots of suppliers, and then returns the receiver.

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

What is lost when a supplier is using Object.assign() to create a mixin?

A

It lossed the accessor properties.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q
What is the following code going to do and why?
var obj = {
      a:1,
      0:1,
      c:1,
      2:1,
      b:1,
      1:1
}

obj. d = 1;
console. log(Object.getOwnPropertyNames(obj).join(“,”));

A

“0,1,2,a,c,b,d” because it groups all numeric keys will be group and sorted, however the string keys will appear in the order they were added.
Also the keys in the object literal come first, followed by the keys added afterwards.

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

What is the key enumeration method for for-in loops, for Object.keys() and for JSON.stringify() ?

A

All have “unspecified” enumeration order

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

How is an object’s prototype specified in JavaScript?

A

In two ways: when the object is created via either a constructor or via Object.create() method.

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

What is the difference between ES5 and ES6 in terms of prototype changing?

A

In ES5 is not allowed, however in ES6 the new method Object.setPrototypeOf(obj, prototype) allows it.
Caveat: it is a very slow operation, better to use Object.create()

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

Do const, let and var need initializers?

A
"const" always requires an initializer;
"let" and "var" need one only when you're using destructuring:
e.g. let node = {
            type: "identifier",
            name: "foo"
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

What happens if you try to read null or undefined in JavaScript?

A

It throws a runtime error.

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

What is the “value” local variable going to be in the code below:

let node = {
       type: "id",
       name:"foo"
};
let  {type, name, value} = node;
A

“value” will be undefined.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q
Having two variables:
let a = 1, b =2;
How do swap them in a single instructions by using destructuring?
A

[a,b] = [b,a]

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

How do you clone arrays in ES5 compared to ES6?

A
In ES5: 
var colors = ["red","blue","green"];
var clonedColors = colors.concat();

In ES6:
let colors = [“red”,”blue”,”green”];
let [ …clonedColors] = colors; //using the rest parameters

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

In ES6, how can you pull out values of a JSON structure?

A
By using mixed object and array destructuring:
let node = {
      type: "id",
      name: "foo",
      loc: {
            start: {
                    line:1,
                    col:1
           },
           end: {
                    line:1,
                    col:4
           }
       }
       range: [0,3]
};
let {
        loc: {start},
        range: [startIndex]
} = node;
console.log(start.line); // 1
console.log(start.col); // 1
console.log(startIndex); //0
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

How do you create a Symbol in ES6?

A

let user_id = Symbol.for(“user_id”);

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

What do you get below?

var uid = Symbol.for("uid");
let desc = String(uid);
console.log(desc+uid);
A

Uncaught Error: Cannot convert a Symbol value to a string

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

What do you have to use to overwrite a nonwritable property of an object?

A

Object.defineProperty()
e.g

let car = { };
Object.defineProperty(car,"speed",{
       configurable:true,
       writable:false,
       value:1})
car.speed; // 1
car.speed = 4;
car.speed; // 1 (unmodified)

Object.defineProperty(car,”speed”,{

   configurable: true,
   writable: false,
   value: 100}) car. speed; // 100 (modified)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

What is the following code doing?

ArraySymbol.hasInstance

A

is checking if “obj” is an instance of Array.
Symbol.hasInstance is a property of every function that can be used to check if an object is an instance of that function

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

What is the console.log( ) below actually display?

function SpecialNumber() { }

Object.defineProperty(SpecialNumber, Symbol.hasInstance, {
value: { function(v) {
return (v instanceof Number) && (v>=1 && v<=100);
});

var two=new Number(2);
console.log(two instanceof SpecialNumber);
A

true, as I managed to change the instanceof method of SpecialNumber class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q
Having two variables:
let colors1 = ["red", "green"],
     colors2=colors1.concat(["blue", "black"], "brown");

What is the console.log(colors2); going to show and why?

A

It is going to show [“red”, “green”, “blue”, “black”, “brown”] because the internal array is being split automatically by JavaScript.

In fact, JavaScript spec says that arrays are automatically split in their components, also that all other types are not.

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

What is the JavaScript realm? Give an example

A

It is an execution environment for JavaScript.

For example, an iframe and its containing page are two different realms. Each has its own global scope with its own copy of global objects.

When passed to a different realm, Arrays create problems because “instanceof Array” call return false.

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

What is Symbol.toStringTag used for?

A

Is to allow the programmer to define what the objects return when call Object.prototype.toString.call(obj )

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

In which mode is not allowed to use “with”?

A

strict mode

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

What is the classes and modules default mode?

A

strict mode

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

How can you convert the following set:

let set = new Set([1,2,3,3,3,5,6])
into an array?
A

let a = […set]; (use the set operator)

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

How do you eliminate duplicates from an Array easily in ES6?

A
By transforming the array into a set (new Set(my_array)) then converting back to an array: uniqueArray =
 [...mySet]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

What happens if I add a key to a (non-weak) set then I erase the key?

A

The set still exists even if I put the key = null, because even if I deleted the external variable key, there is still an internal set reference to that object;

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

Can a weak set store objects and primitive values?

A

Yes for objects, no for primitive values

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

In which ones of the two below is not possible to store primitive objects?
Sets and Weak sets

A

In weak sets.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q
Having a function:
                let f = function( ) { };
and two sets:
                let set = new Set();
                let weak_set = new WeakSet();

then in which is not possible to store f, like in:
set.add(f);
weak_set.add(f);

A

You can store f in both, as f is a function, hence not a primitive value; had it been a primitive value, it would’ve been impossible to store it in the weakset.

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

Which of the two types of sets cannot be used in (for…of) loops?

A

Weak sets, as they are not iterable

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

What is the operator … called in the code below:

let set = new Set([1,2,3,3,3,4]);
array = [ ...set];
A

It is the spread operator

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
70
Q
If we have a weak set:
let set = new WeakSet( ),
        key = { };

What happens if we add a key as in:
set.add(key);

and then we delete the key? What is the key deletion instruction?

A
  1. the key in the set will go, as there is no other key to reference it;
  2. set.delete(key);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
71
Q

What are JavaScript objects always coercing their properties values into?

A

Into strings

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

What can I use as keys when I build a map in ES6?

A

You can use objects, numbers, functions

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

When storing data into a map, assuming the data is in a key/value format, what do you have to do to ensure the data is stored correctly into the map?

A

You have to store the pairs (store,key) in individual arrays:
e.g.

let m = new Map( [ [ “name”, “Nicholas”], [“age”, 25] ] );

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

What is the difference in terms of key-value pairs order between maps and objects when calling forEach()?

A

For maps the key-value pairs will be enumerated in the order of creation, whereas for objects the keys will be enumerated in the order of numeric indexes then in the order of creation for non-numeric keys

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

What is the condition that the keys of a weakmap have to fulfill?

A

They have to be non-null objects

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

Which one is ordered, which one is unordered:

WeakMap, Maps, Sets, WeakSets

A

WeakMaps are unordered;
Maps are ordered;
Sets are ordered;
WeakSets are unordered

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
77
Q
What is missing below:
let w = Weakmap();
A
The correct form is:
let w = new Weakmap();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
78
Q

What is wrong below:

let w = WeakMap();
let w = new WeakMap();
A
  1. Uncaught TypeError: Constructor WeakMap requires ‘new’&raquo_space;> so add “new” to the first statement
  2. Uncaught SyntaxError: ‘w’ has already been declared
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
79
Q

If we have a WeakMap and we add a {key/value} pair, what happens if we delete the key?
What if ,instead of the above, we add an element to the same map: myMap.set( {myKey} ) ==> What happens if we then delete the key?

A

a. The {key, value} will NOT disappear, as only the keys are weakly stored in weak maps;
b. The {key} will disappear;

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

How do you make object properties public or private in ES6?

A

All object properties are public in ES6; whereas in ES5 you have to use IIFEs to create private properties, in ES6 you can use IIFEs and inside them you can use WeakMaps to store private info; the advantage is that doing this way, compared to ES5 way, when the object created by the IIFE constructor disappears, the private info disappears;

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

What is recommended to use instead of nested loops in ES6?

A

You can use iterators

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

What is an iterator?

A

Is an object which:

  1. have a next( ) method;
  2. the next( ) method returns a result object;
  3. the result object has two properties:
    a. value ==> that is the next value;
    b. done ==> a Boolean, true when no more values
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
83
Q

What is a generator?

A

It is a function that returns an iterator

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

Having the following code:

function *createIterator(items){
     items.forEach(function(item)){
                yield item+1;
    });
}

you will get an error; what is the reason?

A

“yield” keyword can only be used inside iterators; technically, in this example “yield” is indeed inside the iterator, however is inside a function within the iterator.
The error will be “unexpected identifier”

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

What is wrong in the following code?

function *createIterator(x) {
     (x) => {
        yield x+1;
     }
}
A

Is not possible to create iterators with arrow functions. You will get “SyntaxError: Unexpected identifier”

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

What is an iterable?

A

It is an iterator with a Symbol.iterator property

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

What is Symbol.iterator?

A

Is a property which specifies a function that returns an iterator for a given object.
Arrays, stes, maps and strings are iterables in ES6 and they have a default iterator specified.

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

What is for-of loop used for?

A

a for-off loop calls next( ) on an iterable each time the loop executes and stores the value from the result object in a variable:

let value = [1,2,3];
for (let num of values){
console.log(num)
}

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

All iterators created by generators are also iterables. Why?

A

Because generators assign the Symbol.iterator by default.

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

What is the code below doing?

return typeof object[Symbol.iterator] === “function”

A

Checking whether an object is iterable

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

How can you access the default iterator of an object?

A

You can use Symbol.iterator as per below:
let values = [1,2,3];
let iterator = valuesSymbol.iterator;

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

Are the developer-defined objects iterable by default?

A

No.

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

How do you make an object iterable?

A

By creating a Symbol.iterator property containing a generator:

let collection = {
       items: [ ],
      *[Symbol.iterator] ( ) {
              for (let item of this.items) {
                    yield item;
              }
       }
};
collection.items.push( 1 );
collection.items.push( 2 );
collection.items.push (3);

for (let x of collection ){
console.log(x);
}

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

What are the default iterators for Weak Maps and Weak Sets?

A

They don’t have built-in iterators;

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

What are the default iterators for arrays, maps, and sets?

A

arrays and maps is values( ), for sets is entries( )

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

Can you use the spread operators several times in an array?

A

Yes:
let smallNumber = [1, 2, 3];
let bigNumber = [100, 200, 300];
let allNumbers = [0, …smallNumbers, …bigNumbers];

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

Why are the iterator return values useful?

A

For delegating operators. The spread operator and the for-of ignore the return value.

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

Can generators be combined?

A
Yes:
function *createNumberIterator ( ) {
  yield 1;
  yield 2;
}
function *createColorIterator ( ) {
   yield "red";
   yield "green";
}
function *createCombinedIterator( ) {
   yield *createNumberIterator( );
   yield *createColorIterator( );
   yield true;
}

var iterator = createCombinedIterator( );

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

What is the yield instruction behaviour?

A

It stops execution and waits for the next( ) method to be called before starting again

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

How do you pass values into an iterator?

A

By passing values into the next( ) method

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

What is yield role in an generator?

A

It stops the generator execution and waits for the next() method to be called before starting again

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

How can you access the default iterator for an object?

A

You have to use the Symbol.iterator, like below:
let values = [1,2,3];
let iterator = valuesSymbol.iterator;
console.log(iterator.next)); // “{value:1, done:false}”
console.log(iterator.next)); // “{value:2, done:false}”
console.log(iterator.next)); // “{value:3, done:false}”
console.log(iterator.next)); // “{value:undefined, done:true}”

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

How do you make a developer-defined object iterable?

A
By creating a Symbol.iterator property that contains a generator:
let collection = {
     items: [],
     *[Symbol.iterator] ( ) {
                for (let item of this.items) {
                     yield item;
                }
     }
};

collection. items.push(1);
collection. items.push(2);
collection. items.push(3);

for (let x of collection) {
console.log(x);
}

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

How many types of collection objects are in JavaScript?

A

three: arrays, maps and sets

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

For the three types of collection objects in JavaScript, enumerate the built-in iterators

A
  1. entries()&raquo_space;> return iterator whose values are key/value pairs;
  2. values()&raquo_space;> return iterator whose values are the values of the collection;
  3. keys()&raquo_space;> return an iterator whose values are the keys contained in the collection;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
106
Q

For the three types of collection objects in JavaScript, which s the default iterator?

A

a. the values() is the default for arrays and sets

b. the entries() is the default for maps

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

What are the built-in iterators for weak sets and weak maps?

A

They DON’T have built-in iterators

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

How do you transform a Set into an Array?

A

by using the spread operator (…)&raquo_space;> for ex:
let set = new Set([1,2,3,3,3,4,5]),
array = […set];
console.log(array);

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

What are the two ways that an iterator can pass values out?

A

a. by using the next( ) method;

b. by using the yield in a generator;

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

How can you pass values into an iterator?

A

By using the next( ) method also; when you pass an argument to the next( ) method, that argument becomes the value of the yield statement inside the generator;

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

How can you pass error conditions into iterators?

A
By building iterators that implement throw( ) method that instructs the iterator to throw an error when it resumes; you can also pass an error object into the throw( ) >>> ex:
function *createIterator( ) {
       let first = yield 1;
       let second = yield first + 2;
      yield second + 3;
}

let iterator = createIterator();

console. log(iterator.next( )); // {value:1,done:false}
console. log(iterator.next(4)); // {value:6,done:false}
console. log(iterator.throw(new Error(“boom”))); // error thrown from the generator

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

How do you catch errors inside the generators?

A

By using the usual try/catch inside the generators

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

What is the second call of console.log( ) in the code below going to produce?

function *createIterator( ) {
      yield 1;
      return;
      yield 2;
      yield 3;
}

let iterator = createIterator( ) ;

console. log(iterator.next( ));
console. log(iterator.next( ));

A

{value:undefined, done:true}

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

Can iterators be combined?

A
Yes, by using generators delegation; for ex:
function *createNumberIterator( ) {
   yield 1;
   yield 2;
}
function *createColorIterator( ) {
    yield "red";
    yield "green";
}
function *createCombinedIterator( ) {
   yield *createNumberIterator( );
   yield *createColorIterator( );
   yield true;
}

let iterator = createCombinedIterator( ) ;
console.log(iterator.next( ));
…………………………….
console.log(iterator.next());

will print:
{value:1,done:false}
{value:2,done:false}
{value:"red",done:false}
{value:"green",done:false}
{value:true, done:false}
{value: undefined, done: true}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
115
Q

Give an example of a generator functions created with an arrow function.

A

It’s NOT possible

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

Can you use generators wherever you use functions?

A

Yes, because generators are actually functions, you can use them both the same way

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

Can you modify a class prototype?

A

No, as they are read-only

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

Are the classes hoisted?

A

Not, unlike function declarations, classes are not hoisted, they are like “let” declaration, that means they exist in the TDZ until the execution point reaches them

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

How can you opt out of the default strict mode in a class?

A

It’s not possible

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

What is the difference between classes and custom types in terms of method enumerability?

A

In classes, all the methods are nonenumerable, whereas in custom types you have to use Object.defineProperty( ) to make a method non-enumerable

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

What is the effect of the code below:

let person = new class {
         constructor(name){
              this.name = name;
        }
        sayName(){
              console.log(this.name);
        }
}("Nicholas");
A

It actually creates a singleton

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

How do you create a default class iterator?

A

By using the syntagm *[Symbol.iterator] inside the class.

For example:

class Collection {
      constructor ( ) {
            this.items = [ ];
     }
     *[Symbol.iterator]( ) { // this expression uses a 
                  // calculated expression that will be the 
                  //generator method, also uses delegation
                  // to the value() iterator of the items;
            yield *this.items.values( );
     }
}
var collection = new Collection( );
collection.items.push(1);
collection.items.push(2);
for (let x of collection) {   // here is how I use the iterator)
    console.log(x);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
123
Q

Can you access static members of a class from its instances?

A

No, you must access static members from its class only

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

What are the rules of using super( )?

A
  1. You can only use super( ) in a derived class constructor; if you use it in a non-derived class (one that doesn’t use “extends”, or in a function, will throw);
  2. You must call super( ) before accessing “this” in the constructor;&raquo_space;> super( ) is responsible to initialize “this”;
  3. the only way to avoid calling super( ) is to return an object from the class constructor;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
125
Q

Are static members of a class inherited or not?

A

Yes

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

Can you dynamically use an expression to calculate the class that I want to extend?

A
Yes. For ex:
function Rectangle( ) { ... }
function getBase( ) {
      return Rectangle;
}
class Square extends getBase( ) {
        .....
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
127
Q

What is the link between using “extends” and calling super( )?

A

They come in conjunction (in pairs): if you use “extends”, you must call super( )

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

What is the difference between ES5 classical inheritance and the ES6 class-based inheritance?

A
In the ES5 classical inheritance, the value of "this" is created first by the derived type, then the base type of the constructor is created;
In the ES6 class-based inheritance, the value of "this" is first created by the base class and then modified by the derived class;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
129
Q

What are the three pillars of metaprogramming in ES6 and how are they used?

A
  1. Symbols are all about Reflection within implementation - you sprinkle them on your existing classes and objects to change the behaviour.
  2. Reflect is all about Reflection through introspection - used to discover very low level information about your code.
  3. Proxy is all about Reflection through intercession - wrapping objects and intercepting their behaviours through traps.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
130
Q

If you have a new class inheriting from a built-in class (like Array, for ex), and if I use a method on this new class, what type of object will it return - will it be the built-in class or the new class?

A

It will be the new class, because the way the Symbol.species behave;

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

Is it possible to change the species of a class?

A

No, you cannot change the Symbol.species.

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

What fo you use Symbol.species for?

A
It's a symbol used to define a static accessor property that returns a function. That function is a constructor to use whenever an instance of the class must be created inside an instance method (instead of using the constructor).
In simple terms, is a method that returns "this" (aka the constructor function)
In practice, you can use it to control the type of a derived class. For example, if you derive a built-in class and you check the type of the result of any method of the built-in class applied on the derived class (by using instanceOf( ) ), you will get the derived class, whereas if you use the Symbol.species in the derived class as a getter, you will get the built-in class type as a result.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
133
Q

Which built-ins have a Symbol.species defined?

A

Array; ArrayBuffer; Map; Promise; RegExp; Set; Typed Arrays

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

How do you get reference to an Array Symbol.species?

A
let mumu = [ ];
mumu.constructor[Symbol.species];
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
135
Q

Where is the new.target property used?

A

Is always used inside class constructors

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

What is an abstract base class?

A

It’s a class that cannot be instantiated directly

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

How can you use new.target to build an abstract base class?

A
// abstract base class
class Shape {
      constructor( ) {
            if (new.target === Shape) {
                 throw new Error("This class cannot be instantiated directly.");
            }
      }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
138
Q

What is the function below doing?

function myFunction(arrayLike) {
      return Array.prototype.slice.call(arrayLike);
}
A

Is used in ES5 to transform an array-like object into an array

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

What is the way to convert an array-like object into an array in ES6?

A
By using the Array.from( ). For ex:
function doSomething( ){
   var args = Array.from(arguments);
   // us args;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
140
Q

What is an array buffer in JavaScript ES6?

A

Is a memory location that can contain a specified number of bytes;

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

How do you create an array buffer in ES6?

A

let buffer = new ArrayBuffer(10); // allocates 10 bytes

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

How do you check the length of a array buffer?

A

using byteLength();

e.g. console.log(buffer.byteLength);

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

How to you change the size of an ArrayBuffer?

A

You cannot change the size of an ArrayBuffer.

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

What is a DataView type in ES6?

A

It is a “window” that allows you to manipulate the memory pointed by an ArrayBuffer

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

How do you define a DataView?

A
By using the DataView constructor. For ex.:
let buffer = new ArrayBuffer(10);
let view = new DataView(buffer);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
146
Q

How do you write into a DataView?

A

By using the DataView setInt (8,UInt), setFloat32, setFloat64, etc.

let buffer = new ArrayBuffer(10);
let view = new DataView(buffer);
view.setInt8(0,4) ==> writes a value of 4 starting with position 0;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
147
Q

How many numeric data types can be written in an ES6 DataView?

A

8 numeric data types:

Int8, UInt8, Int16, UInt16, Int32, UInt32, Float32 and Float64

148
Q
What is the effect of the following code:
let buffer = new ArrayBuffer(10);
let view = new DataView(buffer,5,2);
A

The effect is that variable view covers bytes 5 and 6;

149
Q

What are the 3 properties of a View?

A

A View has three properties:

  1. bufffer&raquo_space;> the buffer that the view is linked to;
  2. byteOffset&raquo_space;> 2nd arg to the DataView constructor
  3. byteLength&raquo_space;> 3rg arg to the DataView
150
Q

Can I have a two DataViews defined over the same ArrayBuffer?

A
Yes. Fo ex:
let buff = new ArrayBuffer(10),
     view1 = new DataView(buffer),
     view2 = new DataView(buffer,5,2);

console. log(view1.buffer === buffer); // true
console. log(view2.buffer === buffer); //true
console. log(view1.byteOffset); // 0
console. log(view2.byteOffset); // 5

151
Q

What is UIClampedArray typed array constructor used for?

A

It converts values >255 to 255 and values <0 to 0

152
Q

What are the few ways of creating a typed array in ES6?

A
  1. By using an ArrayBuffer:
    let buffer = new ArrayBuffer(10),
    view1 = new Int8Array(buffer);
  2. By passing a single number to a constructor:
    let ints = new Int6Array(2); In this case a new ArrayBuffer is allocated which can be accessed with the Buffer property
  3. By passing an Object to the constructor:
    a. I can pass a typed array into the constructor of a typed array, so each element from the 1st typed array will be copied into the 2nd typed array. Also they will have different Buffers; for ex:
    let ints1 = new Int16Array([25,30]);
    let ints2 = new Int32Array(ints1);
    b. An iterable;
    c. An array;
    d. An array-like object;
153
Q

What is the difference between arrays and typed arrays in terms of length property?

A

You can change the size of a normal array by modifying the length( ) property, however you can’t do it with typed arrays;

154
Q

How many iterators have an array() and a typed array?

A

They both have three iterators: keys(), values() and entries()

155
Q

Can you use for-off loops with typed arrays?

A

Yes

156
Q

What is an “iterable”?

A

It is an object with a Symbol.iterator property.

157
Q

Are the iterators created by generators iterables? if yes, why, if no why?

A

Yes, because generators assign the Symbol.iterator by default;

158
Q

What is the advantage of for-of loop?

A

It eliminates the need to track an index; its actually using the values( ) iterator;

159
Q

How do you convert from a typed array into an array?

A
By using the spread operator:
let myTypedArray = new Int16Array([25, 50]);
let intsArray = [...ints];
160
Q

What is Array.isArray( ) going to return if you apply it to a typed array?

A

False

161
Q

What is inserted in a typed array instead of an invalid value?

A
Zero.(but still inserted);
let ints = new Int16Array(['hi']);
console.log(ints.length); // 1
console.log(ints[ 0 ]); // 0
162
Q

What methods of regular arrays are NOT present in a typed array?

A
concat( );
pop( ), push( )
shift( )
splice( )
unshift( )
163
Q

What method are in addition in typed arrays compared to normal regular arrays?

A

set() and subarray()

164
Q

What is Array.from( ) used for?

A

To transform iterables into arrays.

165
Q

Can I have multiple independent “then” methods for a single promise?

A

Yes. For ex:

promise. then(console.log(contents));
promise. then(…..);
promise. then(…);

166
Q

What happens if you don’t attach a rejection handler to a promise?

A

It will fail silently! Always is a good idea to attacha rejection handler, even if the handler is just a console.log(err);

167
Q

Where are the fulfillment and the rejection handlers added in terms of the job queue?

A

After the executor functions finished, at the end of the job queue.

168
Q

How do you check if a function is a Promise in ES6?

A

Pass the object through a Promise.resolve( ) or Promise.reject( )

169
Q

How do you convert a thenable into a Promise?

A

You pass it through Promise.resolve( ) or Promise.reject ( ), depending on the anticipated answer

170
Q

What happens if you pass a non-promise thenable through Promise.resolve( ) or Promise.reject( )?

A

The two methods Promise.resolve( ) and Promise.reject( ) will return a new promise that is called after the then( ) function.

171
Q

Special technique: how do you track potentially unhandled rejections?

A

You add the unhandled rejections to a map:

let possiblyUnhandledRejections = new Map( );
// when a rejection is unhandled, add it to the map
process.on("unhandledRejection", function(reason, promise){
      possiblyUnhandledRejections.set(promise,reason);
});

process.on(“rejectionHandled”, function(promise){
possiblyUnhandledRejections.delete(promise);
});

setInterval(function( ) {

possiblyUnhandledRejections.forEach(function(reason,promise
){
console.log(reason.message ? reason.message : reason);
// do something to handle these rejections
handleRejection(promise, reason);
});
possiblyUnhandledRejections.clear();
],60000);

172
Q

How is a value passed to the fulfillment handler in an ES6 promise?

A

if I pass a value into the resolve( ) function inside an executor function, that value will be passed into the fulfillment validator.

173
Q

Can I have two consecutive catch( ) attached to a promise?

A
Yes. For ex: 
let p1 = new Promise ( function(resolve,reject){
         throw new Error("Explosion");
});
p1.catch(function(error){
         console.log(error.message); // Explosion
         throw new Error("boom");
}).catch(function(error){
         console.log(error.message);
});
174
Q

What are the two methods to pass a value down a Promise chain?

A
  1. Pass a value into the resolve ( ) function;

2. Return a value from a fulfillment handler.

175
Q

In ES6 promises, can I have a then( ) after a catch( )?

A
Yes. For example:
let p1 = new Promise( function(resolve,reject) { reject(4)} );
p1.catch(function(value){
            return value+1;
}).then(value => {
   ....
});
176
Q

Is it possible for the fulfillment handler to receive an array of values? What about the rejection handler?

A
Yes, is possible for the fulfillment handler to receive an array:
let p1 = new Promise(...);
let p2 = new Promise(...);
let p4 = Promise.all([p1,p2]);
p4.then(function(value)){...} // here value is an array.

Rejection handlers always receive a single value rather than an array.

177
Q

Which one is faster:
Promise.resolve(42);

new Promise(function(resolve,reject){
            resolve(42);
})
A

The first one is faster because is not scheduled, like the second one

178
Q

Are static methods in a class inherited in a derived class?

A

Yes

179
Q

Can you inherit from a Promise?

A
Yes:
class MyPromise extends Promise {
     // use default constructor
     success(resolve,reject) {
                return this.then(resolve,reject);
     }
     failure(resolve,reject) {
                 return this.catch(reject);
      }
}
let promise = new myPromise((resolve,reject) => {
       resolve(42);
});

promise.success(value => {
console.log(value);
}).failure(function(value){
console.log(value);
});

180
Q

What is the object shape?

A

Is the collection of properties and methods available on the object.

181
Q

What can you do with Object.preventExtensions( ) ?

A

You can ensure an object’s shape stays the same shape all the time. Similar to it there two more methods: Object.seal( ) and Object.freeze( );

182
Q

What are the differences between Object.preventExtensions( ), Object.seal( ) and Object.freeze( )?

A
  1. Level 1: Object.preventExtensions( ) ===> cannot add properties to objects (throws err in strict mode);
  2. Level 2: Object.seal( ) ===> is Level 1 plus makes all properties “unconfigurable” (cannot change their attributes - like “enumerable”)
    3 .Level 3: Object.freeze( ) ===> makes all properties non-writable, makes the object not extensible;
    Caveat: protection is “shallow”
183
Q

What is the difference between Object.isExtensible( ) and Reflect.isExtensible( ) ?

A

When passed a non-object value, Object.isExtensible( ) returns false, whereas Reflect.isExtensible( ) throws an error

184
Q

What is the difference between Object.getPrototypeOf( ) and Reflect.getPrototypeOf( ) ?

A

When passed a non-object value, Object.getPrototypeOf( ) returns false, whereas Reflect.getPrototypeOf( ) throws an error

185
Q

Which of the two functions is lower level and which has stricter error control?
Object.getPrototypeOf( )
Reflect.getPrototypeOf( )

A

Reflect.getPrototypeOf( ) is lower level and has stricter error control

186
Q

What can you do with Object.defineProperty?

A
  1. you can define an accessor property;
  2. you can make a property read-only;
  3. you can make a property non-enumerable.
    All these in ES5;
187
Q

How can you use a proxy trap to ensure all the arguments of a functions are numbers? Which trap are you going to use?

A

You’ll have to use the “apply” trap:

function sum(...values) {
     return values.reduce( (previous,current) => previous + current,0);
}
let sumProxy = new Proxy(sum, {
            apply: function(trapTarget, thisArg, argumentList){
                    argumentList.forEach((arg) => {
                         if (typeof arg !== "number") {
                            throw new TypeError("All args must be numbers);
                        }
                     });
                     return Reflect.apply(trapTarget, thisArg, argumentList);
             };
});
188
Q

Why would you like a revocable proxy?

A

Due to security reasons, I might want to provide an object through an API, but to cut off some functionality if I want to.

189
Q

How do you create a revocable proxy?

A
By using Proxy.revocable( ); for ex:
let target = { 
            name: "target" 
}
let {proxy, revoke} = Proxy.revocable(target,{ });
console.log(proxy.name; // "target"
revoke( );
console.log(proxy.name); // throws an error
190
Q

What is the effect of the revoke( ) function in a revocable proxy?

A

No further operations can be performed through the proxy.

191
Q

How do you revoke a proxy?

A

Step 1. destructure the Proxy.revocable( ) function:
let [proxy,revoke} = Proxy.revocable(target,{ });
Step 2. use the revoke method:
revoke( );

192
Q

What are the two properties that I need to implement on an ES6 object to make it emulate an array?

A
  1. The “length” property increases when I insert new elements into that object;
  2. The elements of the array are deleted when I reduce the “length” property;
193
Q

(difficult) When I assign an integer value to a property of an array, how do I know if that property key is actually an array index?

A

A String property name is an array index <==> ToString(ToUint32(P)) is equal to P and ToUint32(p) is less than 2^(32)-1.

194
Q

How do you return a proxy from a class constructor? What is the advantage to do that?

A
class myClass {
      constructor ( ) {
             return new Proxy(this, { });
      }
}
When the class in instantiated, the object returned will be a proxy instead of an object. Also, the instance becomes the instance of the proxy;
The advantage is that the instance is completely private!!!
195
Q

When are the proxy traps called if that proxy is used as a prototype?

A

They will called only when the default operation would normally continue on the prototype.

196
Q

Where is the actual operation of defining an object property going to happen? On the actual object or on the actual prototype?

A

Will actually happen on the actual object, not on the prototype.

197
Q

What happens if I create an object using a proxy as a prototype?

A

Then the initial object will have as prototype the taget of the proxy, as the proxy is transparent

198
Q

What do the internal properties [[Get]] and [[Set]] do when they are called on an object?

A

They look at the own properties first. If the own properties don’t exist, the search is continued on the prototype.

199
Q

How do you create an object that throws an error every time a property that doesn’t exist is accessed?

A

By using the “get” Trap on a prototype:

let target={};
let thing = Object.create(new Proxy(target, {
               get(trapTarget,key,receiver){
                     throw new ReferenceError(`${key} doesn't exist);
                }
}));
let unknown = thing.unknown;
200
Q
Having two objects:
let a = { };
let b = Object.create(a);
a.nene=100;

What happens if I do: b.nene=200?

A

Then b.nene=200 and a.nene=100, as the[[Set]] method is acting by default on the instance and not on the prototype!!!

201
Q

Are the classes prototypes writable or non-writable?

A

Non-writable

202
Q

How can you create a class that raises an error when I use a non-existent property?

A

Tricky: by using inheritance from a function that has a proxy with a trap on [[get]];

203
Q

Which are the only proxy traps that are used on a proxy?

A

“get”, “set” and “has”

204
Q

What is the default mode that an ES6 module runs into?

A

ES6 modules run in “strict” mode. There is no way to change that.

205
Q

What is the value of this at the top value of an ES6 module?

A

Undefined

206
Q

How is the default value for an ES6 module established?

A
It is a single variable, single function or a single class specified by "default" keyword:
for ex:
export default function(num1,num2){
     return num1 + num2;
}
207
Q

How can you export a default by using the renaming syntax in ES6 modules?

A
By using {export xxx as default}; for ex:
function sum(num1, num2){
            return num1 + num2;
}
export {sum as default};
208
Q

Do you use curly braces in default imports in ES6 modules? What about in non-default imports?

A

In default imports you don’t use curly braces, however in non-default imports you do;

209
Q

How do you export anonymous functions from ES6 modules?

A

The only way of doing it is by using the “default” keyword.

210
Q

In ES6 module, can you export a function later compared to the moment you define it? If yes, why., if no, why?

A

Yes, because you also export references, not only declarations

211
Q

What is the specific requirement for an ES6 module specifier?

A

For browsers you must use the file extension when you import:
import {id1, id2} from “./example.js”;

212
Q

What is the effect of importing a binding from an ES6 module?

A

It is like the binding was defined with const:

  1. you cannot define another variable with the same name;
  2. you cannot use the identifier before the “import” statement;
  3. you cannot change the binding’s value;
213
Q

How do you import a whole ES6 module and how do you access the imports?

A

You use: import * as example from “./examples.js”

214
Q

What is the rule if you import defaults and non-defaults in an ES6 module?

A

The default comes first and the non-defaults have to be separated by a comma and must use curly brackets from the default. For ex:
import sum, {color} from “./example.js”

215
Q

Can you use “import” in an ES6 module several times and if yes, what happens, if no, why?

A

You can actually use several “import” instructions in an ES6 module, however the module will execute only once.

216
Q

When do you have to include the default import in curly brackets in ES6 modules?

A

When you use the renaming syntax. For ex:

import { default as sum, color } from “./example.js”

217
Q

Is it possible to have ES6 modules that do not export anything? If yes, how do you execute the module, if no, why?

A
Yes, there are cases when ES6 modules do not have exports. In such case you can execute the module by doing a simple "import":
import "./examples.js";
218
Q

How do you re-export everything from an ES6 module?

A

By using:

export * from “./example.js”

219
Q

What is the restriction of re-exporting everything from an ES6 module?

A

The restriction is that if the initial module from which you re-export already has a default export, then you cannot redefine the default export in your module

220
Q

What is the difference between javascript scripts and ES6 modules?

A

Both are files, however the ES6 modules use the keyword “import” which signifies that there are dependencies that must be loaded first. The HTML file should use

221
Q

When using ES6 modules in a web page, what is the condition that must fulfil first before the modules execution starts?

A

First the broswer will have to do the imports and only then the execution starts

222
Q

What are the web workers and how do you create them?

A

Workers (e.g. web workers, service workers), execute Javascript outside of the web page context.
You create a Worker with the constructor “new Worker”;
For ex:
let worker = new Worker(“script.js”);

223
Q

What are the two differences between “worker modules” and “worker scripts”?

A
  1. Worker scripts are subject of the “same origin” restriction, so they must be loaded from the same origin as the web page they’ve been referenced, whereas the worker modules are not, providing they have appropriate CORS headers;
  2. Worker scripts can load “self.importScripts()” to load additional files into the script, however the worker module do not support that instruction, they must use “import” instead;
224
Q

What do you need in ES6 when you want to check that a value is part of an Array but you don’t need its index?

A

You can use myArray.includes(val);

225
Q

What is the return value of myArray.indexOf(NaN)?

A

Is a quirk: it returns -1

226
Q

Regarding the ES6 default parameters, what is the value displayed below?

function getValue(){ return 5}

function add(first, second = getValue( )){
      return first + second;
}

console.log(1);

A

it is 6, because I do not provide the second parameter, so the function getValue( ) is called to retrieve the correct value.

227
Q

What is the value displayed below and why?

for (var i = 0; i<10; i++){
     process(items[i]);
}

console.log(i)

A

the value will be 10, because the “var i” in the loop is hoisted as well in JavaScript

228
Q

What impact have rest parameters on a function’s length property?

A

None, because the functions’ length property only takes into account the named parameters.

229
Q

What are the two destructuring types in ES6?

A

Object and array destructuring

230
Q

When is the ES6 destructuring throwing an error?

A

When the right hand side expression is “null” or “undefined”

231
Q
What will happen in the code below and why?
function setCookie(name, value, options) {
      let {secure, path, domain, expires} = options;
 }
setCookie("type",js);
A

It will throw an error, because the third parameter was not provided to the setCookie function call, so the “options” is “undefined”, which will lead to error throwing in the destructuring;

232
Q

What is a good recommendation on using Symbols?

A

It is a good idea to add Symbol description, as it will make debugging easier;

233
Q

What is the difference between Symbol( ) and Symbol.for( )

A

The Symbol.for( ) is actually using the global symbol registry, whereas Symbol( ) does not save the symbol in the symbol registry

234
Q

What is the resemblence between storing an object in an instance of a Set and storing the object inside a variable?

A

In both cases, as long as there is a reference to that Set or variable, the object in discussion cannot be garbage collected.

235
Q

How can I eliminate the duplicates from an Array?

A

You convert the array to a Set and then reconvert it back to an array:
let set = new Set([1,2,3,3,3,4,5]);
let array = […set]; // use the spread operator

236
Q

How do you make a user-defined object iterable?

A
By creating a Symbol.iterator property containing a generator:
let collection = {
    items: [ ],
    *[Symbol.iterator]( ) {
           for (let item of this.items) {
                yield item;
           }
     }
}

collection.items.push(1);
collection.items.push(2);
for (let x of collection){
console.log(x);
}

237
Q

`What happens in a collection (Array, Set or Map) when no iterator is defined?

A

The default iterator will be used.

238
Q

Can you use the spread operator on any iterable?

A

Yes, and by using it is the easiest way to convert an iterable into an array

239
Q

Can I use ES6 classes as arguments in functions?

A
Yes, because classes are in ES6 first class citizens (like functions);
function createObject(classDef){
     return new classDef( );
}
let obj = createObject(class {
     sayHi( ) {
                 console.log("Hi");
    }
});

obj.sayHi() // Hi

240
Q

How do you change the size of an Array buffer?

A

The size of Array buffers cannot be changed.

241
Q

What is the relation between typed arrays and Array Buffers in ES6?

A

The ES6 typed arrays are actually type-specific views for array buffers.

242
Q

What are the two events that Node.JS emit when a promise is rejected?

A
  1. unhandledRejection&raquo_space;> emitted when a promise is rejected and no rejection handler is called within one turn of event loop;
  2. rejectionHandled&raquo_space;> emitted when a promise is rejected and a rejection handler is called after one turn of event loop.
243
Q

What are the restrictions of prototype proxy traps?

A
  1. the getPrototypeOf( ) trap must return an object or null; any other return value results in runtime error;
  2. the return value of setPrototypeOf( ) must be false if the operation does not succeed;
244
Q

What are the two options when you create a derived class in ES6?

A
  1. You use a constructor and then use “super” inside it;

2. You do not use a constructor (super is automatically called);

245
Q

How do you call a method on the parent class if the derived class has a method with the same name?

A
By using "super":
class Square extends Rectangle {
    constructor(length) {
        super(length, length);
    }
    //override the Rectangle getArea function
    getArea() {
     return super.getArea();
    }
}
246
Q

How does a literal form of a Symbol looks like?

A

Symbols do not have literal form

247
Q

Can Symbols be inherited?

A

yes, objects can inherit Symbols from their prototypes

248
Q

What can be stored in a Weak Set?

A

Only objects. Weak Sets cannot store primitive values.

249
Q

How can you retrieve a key in a Set?

A

[…set][0] for example

250
Q

How can you associate additional data to an object when you don’t want to modify the object?

A
You can use a Map:
let myInitialObject = { ...};
let map = new Map( );
let myAdditionaData={ ...}; //info to be added
map.set(myAdditionalData, myInitialObject);
251
Q

What is the definition of “block scope” that “let” and “const” use in ES6?

A

A “block scope” is the domain inside a function of within { }. It’s inside the block scopes that the “let” and “const” are actually visible.

252
Q

Are the “let” declaration hoisted, and if yes, at which level - block or scope?

A

The “let” declarations are NOT hoisted.

253
Q

What happens if I re-declare with “let” a binding that has already been declared with “var” previously?

A

The “let” declaration will shadow the “var” declaration.

254
Q

What is the mandatory thing to do when you declare a “const” binding?

A

You need to initialize it.

255
Q

What is the difference if you change the “const” declaration binding? Also, what happens if you change the “const” declaration value?

A

If you change the “const” binding you will get an error, however if you change the value you will NOT get an error if and only if the value is an object, otherwise you will get an error.

256
Q

What happens if you access (e.g. with typeof( ) ) a “let” or “const” binding before it’s been declared?

A

You will get a reference error, because that binding will be in the TDZ, so you are not allowed to use it in any way!!!

257
Q

In which kind of loop (for, for-in, for-of) can you actually use “const”, and under which conditions?

A

If you use “const” in for loops, unless you do NOT change the binding, you will get an error.
If you use “const” in “for-in” and “for-of” loops, you will NOT get any error, because for every iteration in these two types of loops a new binding will be created.

258
Q

What happens to the global scope if you use “let” and “const” at that level? What is it different compared to using “var” declarations at the global scope?

A

A new binding will be created and no property will be added to the global scope. That is different to using “var” at the global scope, because in this case (the latter) a new property will be added to the global scope.

259
Q

When do you still use the “var” declarations in ES6?

A

If you use them in global scope in browsers, as they will be available between windows frames.

260
Q

When do you use “let” and when do you use “const”?

A

You use “const” by default, you use “let” when you know that the value of the binding will change. However, stay away from using let because it introduces side effects.

261
Q

What are the code points in ES6 and what are they being used for?

A

They are globally unique indentifiers, simply numbers starting at 0.
They are character codes, and the first 2^16 are called BMP (Basic Multilingual Plane). Everything beyond these points are called supplementary

262
Q

What is the difference between the charCodeAt() and codePointAt() functions?

A

When I apply the two functions to a supplementary Plane code point (so more than 16 bits), the charCodeat() returns only the first code unit, whereas the codePointAt() returns the full code point, even if the code point spans several code units.

263
Q

What types of code units are actually used in the ES6 regexes?

A

Regexes use the 16-bit code points, where each code unit is a character

264
Q

What is the /u flag used for in regexes in ES6?

A

It switches modes to work on characters, not code units.

265
Q

What is the string “length” function returning? Is it the number of code units or the number of code points?

A

It is the number of code units.

266
Q

What is the regex pattern that matches the new lines in ES6?

A

[\s\S], which means match space and non-space characters, INCLUDING NEW LINES

267
Q

Why is it not possible to get the position of a character in a string by using the startsWith(), endsWith() and includes() functions in ES6?

A

Because these functions actually return a Boolean value, but not the actual position of the character. For that, you need to use indexOf()

268
Q

What is the difference between the startsWith(), endsWith() and includes() functions on one side and the indexOf() and lastIndexOf() functions on the other side, in terms of providing them with a regex?

A

startsWith(), endsWith() and includes() will throw an error if I provide them with regexes, whereas the indexOf() and lastIndexOf() will actually convert the regexes into a string and then search for that string

269
Q

What is the repeat() function used in ES6?

A

It is used in strings, is returning a string which is a repeated version of the original string. Is not a function, is actually a method of strings;

270
Q

What is the “y” flag doing in ES6 regexes?

A

It affects the regular expression search’s sticky property. It tells the search to start matching characters in a string exactly at the position specified by the regex’s “lastIndex” property. If there is no match at that location, the regex should stop matching.

271
Q

Ho do you detect if a regex pattern object has the sticky property activated?

A

You can use the sticky property:
let pattern = /hello\d/y;
console.log(pattern.sticky);

272
Q
What is the difference of impact in ES5 and ES6 for the following code:
var re1 = /ab/i;
re2 = new RegExp(re1,"g");
A

In ES5 will throw an error (you cannot use a second argument of a regex constructor when the first argument is a RegEx itself), in ES6 is working fine

273
Q

What flags will the regex have in ES6?
let re1 = /ab/i;
re2 = new RegExp(re1,”g”);

A

It will have only the “g” flag, as the RegExp constructor actually replaces the “i” flag

274
Q

How do you get the source text of a regexp and how do you get the flags of a regexp?

A

You have to use regexp.source and regexp.flags for that

275
Q

How can you create multiline strings in ES5?

A
By using the "\" character; for ex:
var message = "Multiline \
string";
The problem with this approach is that you cannot print it, as "\" is interpreted as a continuation character rather than a newline (bug in ES5). The solution is to use "\n\" instead.
276
Q

Can you use imbricated template literals in ES6?

A
yes. For ex.:
let name= "RSE";
let message = `Hello, ${
         `my name is ${name}`
      }.`;
277
Q

What are the ES6 tagged templates?

A

They are templates which actually perform a transformation on the template literal and returns the final string value.

278
Q

What are the differences between ES6 modules and Node.js modules?

A
  1. The ES6 modules are loaded asynchronously per se, whereas the Node.JS modules are loaded synchronously, which is slower;
  2. ES6 modules are static, meaning they cannot be changed at runtime.
279
Q

What is the definition of a block scope?

A

inside a function or inside {}

280
Q

Are “let” declarations hoisted?

A

No

281
Q

What happens if you declare a variable with “let” after you declared it with “var”?

A

If they are in the same scope, you will get an error “identifier already been declared”;
If they are not in the same scope, the “let” shadows the “var” if the latter was declared before the “let” one.

282
Q

Do you need to initialise entities declared with const and let?

A

Yes with “const”, not with “let”

283
Q

Can I declare a “const” entity if is been already declared?

A

No, if they are in the same scope

284
Q

Are the const declarations hoisted?

A

Nope

285
Q

Are the “const” declarations available outside the block they’ve been defined?

A

Nope

286
Q

Are the “const” and “let” declarations available before they’ve been declared?

A

Nope

287
Q

When are a “const” and a “let” variables behaving similarly?

A

In “for-in” and “for-of” loops.

288
Q

What is typeof of an undeclared variable returning if the variable is in the TDZ?

A

throws an error (“ReferenceError”: cannot access … before initialization”)

289
Q

What is the difference between a variable declared with “var” compared to a variable defined with “let” if they are declared in the global scope?

A

The “var” variable will be attached to the global scope, whereas the “let” variable will not

290
Q
What is the difference between:
var funcs = [ ];
for (var i=0; i<10; i++) {
    funcs.push(function( ) {
         console.log(i);
   });
}

and

for (let i=0; i<10; i++) {
    funcs.push(function( ) {
         console.log(i);
   });
}
A

In the first case, i is shared across each iteration of the loop, so the code declared inside the loop will hold a reference to the same variable; in the end, the console.log(i) will print number 10 ten times; to solve it, you will need an IIFE;
In the second case, you do not need an IIFE, as “let” will actually create a new variable in every step of the loop, and will initialize it with the same name as the previous variable.

291
Q

What happens if you use “const” in a loop?

A

it will behave differently, function of the loop type:

  1. if the loop is a normal “for” loop, you will get an error after the first step: “TypeError: assignment to a constant variable”;
  2. if the loop is “for-in” or “for-of”, a “const” variable declared in the loop will behave similar to a “let”
292
Q

Can you use ES6 template in another template?

A

Yes, is OK ==> for ex:

let name = "Nicholas",
     message = `Hello, ${
                  `my name is ${name}`
            }.`;

console.log(message); // Hello, my name is Nicholas

293
Q
What is the problem with the "timeout" parameter below and with its default value?
function makeRequest(url, timeout, callback) {
     timeout = timeout || 2000;
    callback = callback || function() { } ;
    // the rest of the function
}
A

If is zero, the function will consider it falsy, so will default to 2000 - be careful, tricky

294
Q

If you have a function:
makeRequest(url, timeout=2000, callback) { … }

then which of the following calls will make the timeout value in the function to be 2000:

a) makeRequest(“/foo”, undefined, function(body){…});
b) makeRequest(“/foo”);
c) makeRequest(“/foo”, null, function(body){ … });

A

The answer is: a) and b), as the default params values are assumed only of that param is not provided or if is provided as “undefined”

295
Q

Is the “arguments” object being updated in ES5 or in ES6? If yes, in which mode (strict/unstrict)

A
In ES5 non-strinct mode, the arguments object is updated to reflect changes in named params. For ex:
function fn(first, second) {
   first == arguments[0]; // true
   first = "c";
   first == arguments[0]; // true
}
In ES5 strict-mode, the arguments object is NOT updated after I modify the parameters. ES6 behaviour is the same like in ES5 strict-mode
296
Q
If I have a function:
function fn(first, second="b"){ 
       console.log(arguments.length) 
}
then what is the function calls below going to print?
a) fn("a")
b) fn("a", ,"c");
c) fn("a",undefined, "c")
A

a) 1;
b) Uncaught syntax error: Unexpected token ,
c) 3

297
Q

Can I use a function as a default param value in ES6?

A
Yes; for ex:
function getValue() { return 5}
function add(first, second = getValue()){
      return first + second } 
add(1,1) // 2
add(1) // 6
298
Q

What is TDZ for params in ES6?

A

It means that earlier params do not have access to the later params in a function, but is true the other way around

299
Q

What is the similarity between function params and “let” declarations?

A

In declaring a function param it means you establish a new bounding for that param, also you create a TDZ

300
Q

Why is not possible for a function params to use variables inside that function?

A

Because the scope and the TDZ for the params are separate from the scope and TDZ of that function

301
Q

What is the influence of the rest params on the ‘arguments’ variable of a function?

A

The rest params of the function will always be embedded in the “arguments”

302
Q

How can you manufacture a function from pieces in ES6?

A

const add = new Function(‘first’ ,’second’, ‘return first+second;’). It can be used in functional programming

303
Q

What are the special cases of ES6 function naming mechanism?

A
A. Getters and setters:
var person = {
    get firstName(  ) {
        return 'Nicholas';
    },
    sayName ( ) {
        console.log(this.name);
    }
}
console.log(person.sayName.name); // sayName
console.log(person.firstName.name); // get firstName
B. functions created with bind( ) will prefix their name with "bound" and a space:
var doSomething = function( ) { };
console.log(doSomething.bind( ).name); // "bound doSomething
C. function created with a function constructor will have their name as "anonymous";
let f = new Function('x','y','return x^2+y^2')
console.log(f.name); // anonymous
304
Q

Describe the [[Call]] and the [[Construct]] methods of a function in ES6

A

They are internal methods of functions.
[[Call]] is executed if the function is called without new, so the function body is executed as listed;

[[Construct]] is executed if the function is called with new; what happens is that the [[Construct]] method is creating a new object, called the instance, and then executing the function body with “this” set to the instance.

Not all functions have [[Construct]] (e.g. arrow functions)

305
Q

What is the new.target in ES6?

A
It is a metaproperty (a property of a non-object that provides info related to its target); when a function's [[Construct]] is called, new.target is filled with the target of the "new" operator. That target is typically the constructor of the newly created object instance that will become "this" inside the function.
If [[Call]] is executed, new.target is undefined.
I can use the new.target to safely detect if a function has been called with new:
function Person(name){
   if (typeof new.target !== "undefined") {
      this.name = name;
   }  else {
      throw new Error("You must use new operator");
   }
}
306
Q

Can we have duplicated arguments in ES6 functions?

A

For non-arrow ones, can only have duplicated args only in non-strict;
For arrow ones, they canno have duplicated params;

307
Q

What is the behaviour of arrow functions of one param?

A

They automatically return the expression on the right

308
Q

What do you need in an arrow function if you have more than 1 param?

A

You need brackets around params:

let f = (x,y) => x+y;

309
Q

What are arrow functions used for ideally?

A

In working with arrays

310
Q

Can you use apply( ), call( ), bind( ) on arrow functions? If yes, what is the problem, if no, what is the problem?

A

yes, but you cannot modify the “this” inside the arrow functions by using the three mentioned functions.

311
Q

What is the definition of a tail call?

A
A tail call is when a function is called as the last statement in another function:
function f ( ) {
    return g ( );
}

g( ) is a tail call;

312
Q

Explain the “tail call optimisation” in ES6, also explain why is it useful.

A

In strict mode only, ES6 reduces the call stack for certain tail calls (non-strict mode tail calls are left untouched).
Instead of creating a new stack frame for a tail call, the current stack frame is cleared and reused as long as:
1. The tail call does not require access to vars in the current stack (aka, the function is not a closure);
2. The function making the tail call has no further work to do after the tail call returns;
3. The result of a tail call is returned as the function value; (immediate return).

useful in recurrent problems.

313
Q

What happens if you return a closure from an ES6 strict-mode function?

A

You invalidate the tail call optimisation

314
Q

What happens if you return a function expression from an ES6 function?

A

You invalidate the tail call optimisation.

315
Q

What happens if you return an expression that contains a function from an ES6 function?

A

You invalidate the tail call optimisation.

316
Q

How can you pass an array into a function, without having to worry about “this” binding of the function?

A

By using the spread operator, you will NOT have to use apply( ) any more, and implicitly you will not have to worry about the “this” binding

317
Q

What are arrow functions designed to replace?

A

The anonymous function expressions;

318
Q

What the ES6 object categories?

A
  1. Ordinary objects ==> have allt he default behavior for object in JS;
  2. Exotic objects ==> their internal behavior differ from the ordinary objects; ex: a bound function, an array object, a string object, arguments object, module namespace object, proxy object;
  3. Standard objects ==> they are defined in the ES6 spec; ex: Array, Date, etc.;
  4. Built-in objects ==> Present in a JS execution environment when a script begins to execute; all standard objects are built-in objects
319
Q

What is the “property value shorthand” syntax in ES6? Give an example.

A
function createAnimal( species, age) {
   return {
       species,
       age
    };
}

so basically you can cut out the property value if it matches any of the previously defined variables. What you still need to do is to return the key - the value will be automatically inserted by ES6.

320
Q

What happens if you use the “property value shorthand” syntax but ES6 cannot find in the current scope the previously declared var that corresponds to the property key?

A

A ReferenceError will be thrown

321
Q

On which of the following can you have computed property names?
1. object instances;
2. object literals.
What happens in ES6 compared to ES5 in each case?

A
  1. only object instances can have computed prop names in ES5 (but now object literals);
  2. In ES6 I can have computed prop names in either.
322
Q
What happens in the following code:
let myHorse = {name: "Hannibal"};
let myPonney = {name: "Max"};
myPonney = Object.assign(myPonney, myHorse);
A

myPonney = {name: ‘Hannibal’);

so the Object.assign( ) overwrites the properties from right to left;

323
Q

What is the difference between ES5 and ES6 in what regards duplicated properties of an object?

A

In ES5 they are not allowed, however in ES6 I can have duplicated props, the last declared one will overwrite the previous ones;

324
Q

What is the order of key enumeration for objects?

A

When I enumerate an object with Object.getOwnPropertyNames( ) or Reflect.ownkeys( ), also when I use Object.assign( ):

  1. All numeric keys in ascending order;
  2. All string keys in the order they’ve been added to the obj;
  3. All symbol keys in the order they’ve been added;
325
Q

How can you enumerate the methods of an object?

A
  1. Object.getOwnPropertyNames( );
  2. for-in loop;
  3. Object.keys( );
  4. JSON.stringify( );
326
Q

In ES6, what is “super” pointing to?

A

Is pointing to the current object’s prototype

327
Q

What happens if you use “super” outside of an object’s concise methods?

A
You get a Syntax Error. To be able to use "super" in an object's methods when you use Object.setPrototypeOf( ) then that corresponding method must me a concise method.
For ex:
const french = {
    speak( ) {
       return 'Bonjour';
    }
};
const multilinguist = {
    speak ( ) {
        return `${super.speak( )}, Hola`;
    }
};

Object.setPrototypeOf(multilinguist, french);
multilinguist.speak( ); // “Bonjour, Hola”

328
Q

Why is “super” reference useful in working with objects and prototypes?

A
Because "super" is not dynamic, so a hierarchy of objects always return the right object. For ex:
let person={
   getGreeting( ) {
      return 'Hello';
   }
}
// prototype is person
let friend = {
   getGreeting( ) {
       return super.getGreeting( ) + ', hi!';
   }
};
Object.setPrototype(friend, person);
// now prototype is friend
let relative = Object.create(friend);

console. log(person.getGreeting( )); // “Hello”
console. log(friend.getGreeting( )); // ‘Hello, hi!’
console. log(relative.getGreeting( )); // ‘Hello, hi’

329
Q

Why is “super” reference useful in working with objects and prototypes?

A
Because "super" is not dynamic, so a hierarchy of objects always return the right object. For ex:
let person={
   getGreeting( ) {
      return 'Hello';
   }
}
// prototype is person
let friend = {
   getGreeting( ) {
       return super.getGreeting( ) + ', hi!'; // can use "super" 
                       // because I use concise methods
   }
};
Object.setPrototype(friend, person);
// now prototype is friend
let relative = Object.create(friend);

console. log(person.getGreeting( )); // “Hello”
console. log(friend.getGreeting( )); // ‘Hello, hi!’
console. log(relative.getGreeting( )); // ‘Hello, hi’

330
Q
What is the third log in the code below going to print?
let person={
   getGreeting( ) {
      return 'Hello';
   }
}
// prototype is person
let friend = {
   getGreeting( ) {
       return Object.getPrototypeOf(this).getGreeting.call(this) + ', hi!';
   }
};
Object.setPrototypeOf(friend, person);
// now prototype is friend
let relative = Object.create(friend);

console. log(person.getGreeting( )); // “Hello”
console. log(friend.getGreeting( )); // ‘Hello, hi!’
console. log(relative.getGreeting( )); // ????????

A

Uncaught RangeError: Maximum call stack size exceeded.

The reason is not very obvious:
When relative.getGreeting( ) is called, there is no getGreeting( ) on the “relative” obj, so the call goes up on the proty chain, but keeping “this” to the initial level (pointing to the “relative”), so when friend.getGreeting( ).call( ) is called with “relative” as “this”, the process starts over again and continues to call recursively until a stack overflow occurs!!!

The solution is to use “super.getGreeting( )” and concise methods instead of “Object.getPrototypeOf(this).getGreeting.call(this);

331
Q

What do you have to wrap a destructuring assignment into?

A

You have to use brackets:
( { type, name } = node );
The reason is that an opening curly brace is expected to be a block assignment, so I need to add a bracket to prevent mis-interpretation

332
Q

What is the destructuring assignment evaluating to in ES6?

A
Is evaluating to the right side of the expression (after the = ). That means you can use a destructuring assignment expression anywhere a value is expected. For ex:
function outInfo ( value) { ... };
let node = {
   type: 'Bla Bla Bla;
   name: 'foo'
};
let type = "x";
let name=5;
outInfo ( { type, name } = node); // type='Bla, Bla, Bla', name='foo'

So above, even if the destructuring is doing it’s job as usual, reassigning “type” and “name”, the function outInfo( ) will be called with “node”;

This destructuring assignment is applied large scale in React.

333
Q

What happens in destructuring assignment if the right side of that expression (the expression after =) evaluates to “null” or “undefined”?

A

It results in a run time error

334
Q
What value will "weight" have in the code below?
let node = {
    type: "Id",
    name: 'foo'
};
let {type, name, weight = 100 } = node;
A

Will be 100, as “weight” prop doesn’t exist on node, so “weigth” will be destructured to the default value; had it been a “weight” prop on “node”, it would have takes that value.
This happens only when the source object in destructuring doesn’t have that prop or if that prop on node has an “undefined” value;

335
Q
What is the following code going to result into?
let node = {
   type: 'id',
   name; 'foo'
};

let {type: localType, name: localName} = node;

console. log(localType);
console. log(localName);

A

localType&raquo_space;»> ‘id’;
localName&raquo_space;»> ‘foo’

This technique is used to assign destructuring assignment values to different local vars

336
Q

What type of technique in ES6 is actually inverse to the object literal syntax?

A

It is the assignment of different local variables by using destructured assignment, because in this case the name is on the right and the location of the value to read is on the left:
For ex:

let node = {
   type: 'id',
   name; 'foo'
};

let {type: localType, name: localName} = node;

337
Q

How do you add a default value to a local var by using destructured assignment in ES6?

A
let node = {
   type: 'id',
   name; 'foo'
};

let {type: localType, name: localName = “bar”} = node;

338
Q

What is the meaning of the “:” and what is the meaning on right side in ES6 object destructuring?

A

The colon “:” means that the identifier before the colon is giving a location to inspect, and the right side assigns a value;

339
Q

What is the meaning of a curly brace after a colon “:” in ES6 object destructuring?

A
It indicates that the destination is nested another level into the object.
For ex;
let node = {
   type: 'id',
  name: 'foo',
  loc: {
      start: {
          line: 1,
          column: 4
      }
   }
};

let {loc : { start }} = node;

console. log(start.line); // 1
console. log(start.column); //1

340
Q

Can you use the assignment to local vars by using nested destructuring assignment in ES6?

A
Yes. For ex:
let node = {
   type: 'id',
  name: 'foo',
  loc: {
      start: {
          line: 1,
          column: 4
      }
   }
};
let {loc: { start: localStart}} = node;
console.log(localStart.line); // 1
console.log(localStart.column); //1
341
Q

What is the effect of this code:

let {loc: { } } = node;

A

no effect, because even if { } are perfectly legal in object destructuring, in here they don’s create any binding!!!

342
Q

What do you have to provide when use var, let or const in object/array destructuring?

A

You have to always provide initializers:

let [ , , thirdColor ] = [ “red”, “yellow”, “green”];

343
Q

How do you copy an array by using rest items in an array?

A

let […clonedArray] = myArray;

344
Q

Can you use mixed destructuring in ES6? (array and object)

A
Yes. For ex:
let node = {
   type: "id",
   name: "foo",
   loc: {
      start: {
         line:1,
         col: 1
      }
   },
   range: [0,1,2,3,4]
};

let {
loc: { start },
range: [ startIndex ]
} = node;

console. log(start.line); // 1
console. log(start.column); // 1
console. log(startIndex); // 0

345
Q

Can you use destructuring in function params?

A

Yes. For ex:
function setCookie(name, value, { secure, expires } ) {
…….
}
setCookie(“type”, “js”, {secure: true, expires: 6000} );

346
Q

What happens in the code below - explain why:
function setCookie(name, value, { secure, path, expires } ) {
…….
}
setCookie(“type”, “js”, {secure: true, expires: 6000} );

A

Error, due to missing params in the destructuring.

Once again, destructuring throws an error when the right side expression evaluates to null or undefined.

347
Q

How do you make a destructured param optional in an ES6 function?

A
By providing a default value for the destructured param. For ex:
function setCookie(name, value, { secure, path } = { } ) {
    ...........
}
348
Q

Assuming you have a function having a mandatory arity, how do you ensure you throw an error every time you don’t provide an argument when you call it?

A

You build a helper function that throws, and then you use that function as a default value for the params of your function:

const required = ( ) => { throw new Error('Missing param')};
// then use that helper 
const add = (a = required( ), b = required( )) => a+b;
349
Q

How can you balance brackets into a string in ES6?

A

By using array reduce function.

350
Q

How can you clean an object of props with sensitive info or because they are too big?

A

Use destructuring to extract them and store the object into the rest parameter. For ex:
let {_internal, tooBig, …cleanObject} = {el1: ‘1’, _internal: ‘secret’, tooBig: { }, el2: ‘2’};
console.log(cleanObject); // {el1:’1’, el2:’2’}

351
Q

How do you use shorthand notation and nested object destructuring in a function params to extract exactly the info you want?

A
For ex:
const car = {
   model: 'bmw 2018',
   engine: {
       v6: true,
       turbo: true,
       vin: 12345
    }
};
const modelAndVIN = ( { model, engine: { vin } } ) => {
    console.log(`model: ${model} vin:${vin});
};

modelAndVIN(car); // “model: bmw 2018 vin: 12345”

352
Q

Can you merge objects with the spread operator?

A
Yes, for ex:
let obj1 = {a:1, b:2, c:3};
let obj2 = {b:30, c:40, d:50};
let merged = {...obj1, ...obj2}; // {a:1, b:30, c:40, d:50}
353
Q

How can you retrieve multiple values from a Promise function?

A

Using Promise.all and async/await:

async function getFullPost ( ) {
   return await Promise.all ( [
        fetch('/post'),
        fetch('/comments')
    ] );
}

const [post,comments] = getFullPost( );

354
Q

What is the similarity between the global scope and the global symbol registry?

A

They both are shared environments. You have to ideally use namespaces when working with them, to avoid clashes with external libraries:
let ctex.uid = Symbold.for(‘uid’);

355
Q

Where is Symbol.hasInstance( ) method defined?

A

Is defined on Function.prototype, so every function has it.

356
Q

How many arguments does Symbol.hasInstance( ) method have?

A

A single param: the value to check. It return “true” if the value is an instance of the function. For ex:
obj instanceof Array;

is equivalent to:

ArraySymbol.hasInstance

357
Q

How do you overwrite a non-writable property in ES6?

A

By using Object.defineProperty.

358
Q

What is the condition of the left operand of the instanceof to trigger the Symbol.hasInstance?

A

It has to be an object

359
Q

What is the instanceof going to return if applied to non-objects?

A

false

360
Q

How do you make a complex object behave like an array in ES6? Explain how and why.

A

By using Symbol.isConcatSpreadable( ). If it is attached to an object, it will “spread” the complex object into an array when I pass that object to the array.concat( ) function.
For ex:
A. var alpha = [‘a’, ‘b’, ‘c’],
numeric = [1, 2, 3];

numeric[Symbol.isConcatSpreadable] = false;
var alphaNumeric = alpha.concat(numeric); 

console.log(alphaNumeric); // Result: [‘a’, ‘b’, ‘c’, [1, 2, 3] ] // the array is NOT flattened

B. var x = [1, 2, 3];

var fakeArray = { 
  [Symbol.isConcatSpreadable]: true, 
  length: 2, 
  0: 'hello', 
  1: 'world' 
}

x.concat(fakeArray); // [1, 2, 3, “hello”, “world”]

Obs. “length” property is crucial, if the object does not have it that it will not spread;

361
Q

What is Symbol.toPrimitive?

A

It is a method defined on the prototype of each standard type object, and prescribes how the object is converted into a primitive.
This method is called with only one argument, the so called “hint”, which is one of the 3 strings values:
1. “number”;
2. “string”;
3. “default”

362
Q

What are the steps that the Symbol.toPrimitive method is taking if is passed a “number”?

A

For most standard objects:

  1. calls the valueOf( ) method, and if the result is a primitive, it returns it;
  2. otherwise, call the toString( ) method, and if the result is primitive, it returns it;
  3. Otherwise it throws an error;
363
Q

What are the standard objects in JavaScript?

A

They are also called “global objects” (not to be confused with “global object”). They are categorised as follows:

A. Value properties: global properties return a simple value; they have no properties or methods. Ex. Infinity, NaN, undefined, null, globalThis (which contains the global object);
B. Function properties: These global functions—functions which are called globally rather than on an object—directly return their results to the caller. For ex: eval( ), uneval( ), isFinite( ), isNaN( ), parseFloat( ), parseInt( ), decodeUri( ), etc;
C. Fundamental objects: These are the fundamental, basic objects upon which all other objects are based. This includes objects that represent general objects, functions, and errors. For ex: Object, Function, Boolean, Symbol, Error, EvalError, InternalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError.
D. Numbers and dates: base objects representing numbers, dates, and mathematical calculations. For ex: Number, BigInt, Magth, Date.
E. Indexed Collections: collections of data which are ordered by an index value. This includes (typed) arrays and array-like constructs. For ex: Array, Int8Array, …;
F. Keyed collections: These objects represent collections which use keys; these contain elements which are iterable in the order of insertion. For ex: Map, Set, WeakMap, WeakSet.
G. Structured data: hese objects represent and interact with structured data buffers and data coded using JavaScript Object Notation (JSON). For ex: ArrayBuffer, SharedArrayBuffer, Atomics, DataView, JSON.
H. Control abstraction objects: Promise, Generator, GeneratorFunction, AsyncFunction;
I. Reflection: Reflect, Proxy;
J. Internationalization: Intl, Intl.Locale, etc;
K. WebAssembly. For ex: WebAssembly, WebAssembly.Module, etc.
L .Other: e.g. arguments

364
Q

What is global scope in ES6?

A

It consists of the properties of the global object, including inherited properties, if any.

365
Q

What happens if you pas an empty descriptor to the Object.defineProperty( ) method?

A

{value: undefined, writable: false, enumerable: false, configurable: false}

366
Q

Which one of the two methods actually exist in ES6: the onc called Object.defineProperties() or the one called Object.defineProperty()?

A

Actually both

367
Q

What are the optional params in Object.defineProperty( ) method?

A

get and set