JavaScript Flashcards

1
Q

What is a Promise?

A

A Promise is a special JavaScript object. It produces a value after an asynchronous (aka, async) operation completes successfully, or an error if it does not complete successfully due to time out, network error, and so on.

Successful call completions are indicated by the resolve function call, and errors are indicated by the reject function call.

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

What is asynchoronous?

A

Refers to the management of a single thread that can move past tasks that are waiting to complete the rest of the program. Synonymous with non-blocking.

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

Can you overwrite variable declarations without an error using var?

A
Yes;
var camper = 'James';
var camper = 'David';
console.log(camper);
// logs 'David'
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What will let math = 12 + ‘13’; console.log to?

A

1213

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q
What is the result of this:
const s = [5, 6, 7];
s = [1, 2, 3]; // ????
s[2] = 45; // ??????
console.log(s); // ?????
A

s = [1, 2, 3]; // throws error, trying to assign a const
s[2] = 45; // works just as it would with an array declared with var or let
console.log(s); // returns [5, 6, 45]

Objects (including arrays and functions) assigned to a variable using const are still mutable. Using the const declaration only prevents reassignment of the variable identifier.

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

What function prevents data mutation of an object?

A

Object.freeze(obj);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q
const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;

arr2 = arr1;

arr1[0] = ‘OCT’
console.log(arr2); /// what does this log?

A

[ ‘OCT’, ‘FEB’, ‘MAR’, ‘APR’, ‘MAY’ ]

arr1 and arr2 are referencing the same array (object), so when arr1 is update, arr2 is updated.

To make an array that won’t change with arr1, use the spread operator:
arr2 = […arr1]

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

What does Array.shift() do?

A

Removes the first item from an array

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

let array = [‘today’, ‘was’, ‘not’, ‘so’, ‘great’];
let splice = array.splice(2, 2);
What are the values of array and splice?

A

array now equals [‘today’, ‘was’, ‘great’]
splice equals [‘not’, ‘so’]
(removes 2 elements beginning with the 2nd index)

Array.splice(starting index, how many to remove, (optional items to add in place))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q
const arr = ['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']
const newArr = arr.slice(2, 4)
What is newArray?
A

[ ‘warm’, ‘sunny’ ]
arr.slice() returns a new array and takes in up to 2 arguments- first the starting index and second the ending index (not included).
arr will return the same array as it is not affected

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

What are data structures?

A

Techniques for storing and organizing data that make it easier to modify, navigate, and access. Data structures determine how data is collected, the functions we can use to access it, and the relationships between data.

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

What makes JavaScript functions first class objects?

A

a function can be assigned to a variable, passed around as an argument to another function and can also be returned from another.

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

What does this return?

console.log(square(5));

var square = function(n) { 
  return n * n; 
}
A

TypeError: square is not a function

If you define a function as a variable, the variable name will be hoisted but you cannot access until JS execution encounters its definition.

If this was not assigned to a variable, would not return an error.

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

What are the six falsy values?

A

undefined, null, NaN, 0, “” (empty string), and false

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

Will these return true or false?

1) false == “”
2) NaN == undefined
3) 0 == null
4) null == undefined
5) NaN == NaN
6) 0 == “”

A

1) false == “”, true
2) NaN == undefined, false
3) 0 == null, false
4) null == undefined, true
5) NaN == NaN, false (NaN is not equivalent to anything, not even itself!)
6) 0 == “”, true

If can use Object.is(NaN, NaN) to see if it is equal (will return true)

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

What are the 6 primitive data types of JavaScript?

A
undefined
Boolean
Number
String
BigInt
Symbol
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How do you make a new object, using an existing object as the prototype of the newly created object?

A

let obj = Object.create(proto, [descriptors])

Example:
let animal = {
  eats: true
};
// create a new object with animal as a prototype
let rabbit = Object.create(animal);

Technically, we can get/set [[Prototype]] at any time. But usually we only set it once at the object creation time and don’t modify it anymore. Changing a prototype “on-the-fly” with Object.setPrototypeOf or obj.__proto__= is a very slow operation as it breaks internal optimizations for object property access operations.

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

Can inherited properties of an object be overwritten?

A

Yes!

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

What is a JavaScript object?

A

An object is a collection of properties, and a property is an association between a name (or key) and a value. The object can contain any data types (numbers, arrays, object etc.)

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

Describe encapsulation.

A
Refers to bundling data with methods that can operate on that data within a class
It is the idea of hiding data within a class, preventing anything outside that class from directly interacting with it
Members of other classes can interact with the attributes of another object through its methods
It’s generally best to not allow external classes to directly edit an object’s attributes
Prevents data from getting into unwanted states
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Describe abstraction

A

Refers to only showing essential details and keeping everything else hidden
Users of the classes should not worry about the inner details of those classes and should not directly interact with other classes’ data
If classes are entangled, then on change creates a ripple effect that causes many more changes
Creating an interface through which classes can interact ensures that each piece can be individually developed

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

What is the difference between encapsulation and abstraction

A

Abstraction is about hiding unwanted details while giving out the most essential details, while Encapsulation means hiding the code and data into a single unit e.g. class or method to protect the inner working of an object from the outside world. In other words, Abstraction means extracting common details or generalizing things.

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

What is polymorphism and what is the difference between static and dynamic polymorphism?

A

Polymorphism is the ability to call the same method on different objects and have each of them respond in their own way.
Dynamic:
-Occurs during the runtime of the program (when it is being executed)
-Describes when a method signature is in both a subclass and a superclass
-The methods share the same name but have different implementation
-The subclass that the object is an instance of overrides that of the superclass
Static:
-Occurs during compile-time rather than during runtime
-Refers to when multiple methods with the same name but different arguments are defined in the same class
-Despite the methods having the same name, their signatures are different due to their different arguments

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q
What will this print:
function Foo(){
    console.log(this);
}
A

It prints the window object because this is a global object. Whatever parent scope is, it will be inherited by the child.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q
let obj1 = {name: 'GreenRoots'};
let obj2 = {name: 'GreenRoots'};

obj1 == obj2 // ???
obj1 === obj2 // ???
Object.is(obj1, obj2); // ???

A

They all return false because non-primitive data types are passed by reference (unlike primitive types that are passed by value).
Hence both obj1 and obj2 the value at the different memory locations that they are created on.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q
What will this return in strict mode and non-strict mode?
function f1() {
  return this;
}
A
Non-strict:
// In a browser:
f1() === window; // true
// In Node:
f1() === globalThis; // true

Strict:
f1() === undefined; // true

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

What is execution context? Explain 2 types.

A

An execution context is an abstract concept of an environment where the JavaScript code is evaluated and executed.

  • Global execution context: The code that is not inside any function is in the global execution context. It performs two things: it creates a global object which is a window object (in the case of browsers) and sets the value of this to equal to the global object.
  • Functional execution context: Every time a function is invoked, a brand new execution context is created for that function. Each function has its own execution context, but it’s created when the function is invoked or called.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What is a lexical environment?

A

A structure that holds identifier-variable mapping, where identifier refers to the name of variables/functions, and the variable is the reference to actual object or primitive values.
Every time the JavaScript engine creates an execution context to execute the function or global code, it also creates a new lexical environment to store the variables defined in that function during the execution of that function.

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

Why is Math.max() smaller than Math.min()?

A

If no arguments are given, Math.min() returns infinity and Math.max() returns -infinity . This is simply part of the specification for the max() and min() methods, but there is good logic behind the choice.

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

How does a function expression differ from a function declaration?

A

Function declarations are hoisted, which means they are moved to the top of their scope by the interpreter. This allows you to call it anywhere in your code. You can only call function expressions linearly. Thus function expressions are more predictable and structured. Assigning them to let and const also provides control is it can be re-assigned or not.

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

What are the differences between var, let, and const?

A
Const can't be reassigned (although does allow for variable mutation... just can't re-assign the variable itself). Const also can't be declared without a value... will have syntax error
All declarations (function, var, let, const and class) are hoisted in JavaScript, while the var declarations are initialized with undefined, but let and const declarations remain uninitialized.
During compile time, JavaScript only stores function and variable declarations in the memory, not their assignments (value). 
They will only get initialized when their lexical binding (assignment) is evaluated during runtime by the JavaScript engine. 
Var is function scoped while let and const are block scoped (scoped within things like if statements and for loops
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What is hoisting?

A

During compile phase, just microseconds before your code is executed, it is scanned for function and variable declarations. All these functions and variable declarations are added to the memory inside a JavaScript data structure called Lexical Environment. So that they can be used even before they are actually declared in the source code. Conceptually, a strict definition of hoisting suggests that variable and function declarations are physically moved to the top of your code, but this is not in fact what happens. Instead, the variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code. One of the advantages of JavaScript putting function declarations into memory before it executes any code segment is that it allows you to use a function before you declare it in your code

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

What is temporal dead zone?

A

A time span between variable creation and its initialization where they can’t be accessed.

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

What will this output?
let a;
console.log(a);
a = 5;

A

Undefined.
Here during the compile phase, the JavaScript engine encounters the variable a and stores it in the lexical environment, but because it’s a let variable, the engine does not initialize it with any value.* *Would have same result with var because the assignment does not get hoisted, just the variable name.
During the execution, when the engine reaches the line where the variable was declared, it will try to evaluate its binding (value), because the variable has no value associated with it, it will assign it undefined.

Without the declaration of “let a” at the top, the output would be a Reference Error: a is not defined.

console.log(a); 
var a = 5;

This however would not return an error but show undefined (variable name hoisted, but not assignment.)

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

What are things not allowed in ‘use strict’

A

Strict mode changes previously accepted “bad syntax” into real errors.

  • Using a variable, without declaring it, is not allowed like x=5
  • Mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.
  • assigning values to non-writable properties
  • deleting a variable or function
  • duplicating parameters
  • The this keyword refers to the object that called the function. If the object is not specified, functions in strict mode will return undefined and functions in normal mode will return the global object (window):
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

What happens if you assign a variable without a keyword?

A

If not using strict mode, it will be assigned to the window. So x = 1 will be window.x = 1

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

Describe Object Oriented Programming.

A

OOP is based around the concept of “objects”. These are data structures that contain data fields — known in JavaScript as “properties” — and procedures — known as “methods”.
Some of JavaScript’s in-built objects include Math (used for methods such as random , max and sin ), JSON (used for parsing JSON data), and primitive data types like String , Array , Number and Boolean .
Whenever you rely on in-built methods, prototypes or classes, you are essentially using Object-Oriented Programming

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

What are the 4 main principles of Object Oriented Programming?

A

Encapsulation, abstraction, inheritance, and polymorphism

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

Explain functional programming.

A

FP is based around the concept of “pure functions”, which avoid shared state, mutable data and side-effects. Given the same inputs, a pure function always returns the same output. It does not have side effects

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

What’s the difference between imperative and declarative programming?

A

Imperative programming is concerned with how you do something. It spells out the steps in the most essential way, and is characterized by for and while loops, if and switch statements, and so on. OOP is an example of imperative programming.
Declarative programming is concerned with what to do, and it abstracts away the how by relying on expressions. This often results in more concise code, but at scale, it can become more difficult to debug because it’s that much less transparent. Functional programming is an example of declarative programming.

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

What is a closure?

A

A closure is the combination of a function and the lexical environment (the scope of the function- identifiers it has access to) within which that function was declared. In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

What makes closures powerful is when a function is returned from another function. When a function is declared in a function, but returned and run outside of where it was declared it will still have access to the scope it was declared in because of closure.

The inner function will have access to the variables in the outer function scope, even after the outer function has returned.
In JavaScript, closures are the primary mechanism used to enable data privacy. When you use closures for data privacy, the enclosed variables are only in scope within the containing (outer) function. You can’t get at the data from an outside scope except through the object’s privileged methods (any exposed method defined within the closure scope)

const getSecret = (secret) => {
  return {
    get: () => secret
  };
};
console.log(secret)
// ReferenceError: secret is not defined
const obj = getSecret(1);
const actual = obj.get();
console.log(actual)
//1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What is scope and describe the types.

A

Scope determines the accessibility of variables. Scope determines where the identifier, such as a variable or function name, is visible and accessible.
Variables declared within a function have local scope and can only be accessed from within the function.
A global variable has global scope and all scripts and functions on a web page can access it.

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

What are prototypes?

A

Prototypes are the mechanism by which JavaScript objects inherit methods and properties from one another.

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

What is a ReferenceError and name common examples.

A

A ReferenceError indicates that an invalid reference value has been detected.
A JavaScript program is trying to read a variable that does not exist:
dog
dog = 2 (need use strict)
Or there are unexpected assignments (such as using = when you should use ==

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

What is a SyntaxError and name some examples.

A
  • A function statement without name
  • Missing comma after an object property definition
  • Trying to use a reserved identifier like delete or class
  • Missing ) or } or ; or ,
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

What is a type error and name some examples.

A

A TypeError happens when a value has a type that’s different than the one expected

  • Mistyping a method… blank is not a function
  • Unexpected undefined and null types
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

Describe Node.js. List benefits and drawbacks.

A

Node.js is a JavaScript runtime built on Chrome’s v8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O (in-out) model that makes it lightweight and efficient. Node.js’ package ecosystem, npm, is the largest ecosystem of open source libraries in the world. A runtime is something that provides custom functionality so various tools and libraries specific to the environment (it is not a programming language).

Benefits:

  • It re-uses Javascript- meaning a front-end Javascript developer can also build an entire server themselves
  • It’s easily extendable- numerous plugins exist to expand on the capabilities of Node
  • Fast-implementation- which allows for the creation of an entire working server with only a few lines of code
  • Single-threaded asynchronous model- meaning it can handle multiple requests simultaneously and not get bottlenecked
  • It is non-blocking because Node uses other threads in C++ to manage your events
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

Name some examples of Web APIs

A

DOM (document), AJAX (XMLHttpRequest), Timeout

49
Q

What is a RESTful API and what are its fielding constraints?

A

1) The network must be made up of clients and servers. A non-RESTful alternative to client-server architecture is event-based integration architecture. In this model, each component continuously broadcasts events while listening for pertinent events from other components. There’s no one-to-one communication, only broadcasting and eavesdropping
2) Stateless- Stateless does not mean that servers and clients do not have state, it simply means that they do not need to keep track of each other’s state. When a client is not interacting with the server, the server has no idea of its existence. The server also does not keep a record of past requests. Each request is treated as a standalone.
3) Uniform interface- ensures that there is a common language between servers and clients that allows each part to be swapped out or modified without breaking the entire system. This is achieved by:
- identification of resources (each resource must be uniquely identified by a stable identifier),
- manipulation of resources through representations (client manipulates resources through sending representations to the server… usually JSON. The server takes the request as a suggestion, but still has ultimate control)
- self-descriptive messages (contains all the info the recipient needs to understand it)
- hypermedia- data from the server to client that contains info on what to do next (like links and buttons)
4) Caching, layered system- RESTful APIs are cacheable due to because of the self-descriptive messages. Layered system refers to the fact that there can be more components than just servers and clients. Each component is constrained to only see and interact with the very next layer. Example layers include proxies and gateways

50
Q

What is a rest operator? What is a spread operator? What is the difference between the two?

A

Rest operator gathers/collects items. It can be used in destructuring items and must be placed last. Spread operator allows an iterable (such as an array) to spread/expand individually inside receiver. It spits items into single items and copies them. Use rest when declaring functions and spread when invoking the function

51
Q

What does Array.from() do and when would you use it?

A

Returns Array object from an object with a length property or an iterable object. Turns array-like into array -string, nodeList, Set. For example, if you use a querySelectorAll to grab a nodeList, using Array.from() you can then use array methods on the list.

52
Q

“Special numeric values” including Infinity, -Infinity, and NaN fall into the “Number” data type. True or False

A

True!

53
Q

Name the differences between Number() and parseInt()

A

Number() converts the type whereas parseInt() parses the value of input. parseInt will parse up to the first non-digit character.

parseInt(‘32px’); // 32
Number(‘32px’) // NaN

parseInt(‘5e1’); //5
Number(‘5e1’); //50

54
Q

What does this return?

alert(“1” + 2 + 2);

A

“122”

Here, the first operand is a string, the compiler treats the other two operands as strings too. The 2 gets concatenated to ‘1’, so it’s like ‘1’ + 2 = “12” and “12” + 2 = “122”.

55
Q

What does this return?

alert(2 + 2+ “1”);

A

“41”

Here, operators work one after another. The first + sums two numbers, so it returns 4, then the next + adds the string 1 to it, so it’s like 4 + ‘1’ = ‘41’.

56
Q
let counter = 1
let a = ++counter;
****************
let counter = 1
let a = counter++;

What is the value of a in each situation and why?

A

In the first scenario, ‘a’ returns 2 because the prefix form returns the new variable.

In the second scenario, ‘a’ returns 1 because the postfix form returns the old variable (prior to increment/decrement).

Note that if the result of increment/decrement is not used, there is no difference in which form to use:
let counter = 0;
counter++;
++counter;
alert( counter ); // 2, the lines above did the same

57
Q

What is the result of these two expressions?
null + 1 = ?
undefined + 1 = ?

A

null + 1 = 0
null becomes 0 after the numeric conversion

undefined + 1 = NaN
undefined becomes NaN after the numeric conversion

58
Q

What is the result of the following expressions?

console. log(“2” > 1);
console. log(“01” == 1);

A

Both are true because when comparing values of different types, JavaScript converts the values to numbers

59
Q

What does this do?

console.log(!!”non-empty string”)

A

Returns true. A double NOT !! is sometimes used for converting a value to a boolean type
Same as:
console.log(Boolean(“non-empty string”)); //true

60
Q

What will this result be?

console.log(null || 2 && 3 || 4)

A

The precedence of AND && is higher than ||, so it executes first.

&& returns the first falsy value or the last value if no falsy is found.

The result of 2 && 3 = 3, so the expression becomes:
null || 3 || 4
Now the result is the first truthy value: 3

61
Q

When would you want to use “do…while” over “while”?

A

This form of syntax should only be used when you want the body of the loop to execute at least once regardless of the condition being truthy. Usually, the “while” is preferred

62
Q

What is the nullish coalescing operator ?? and how is it differ from the OR || operator?

A

|| returns the first truthy value.
?? returns the first defined value.

We use ?? when we want to use default value only when the variable is null/undefined (instead of false, 0, “”). That is, when the value is really unknown/not set.

63
Q
let obj = {
   3: "test"
}
What do these return?
console.log(obj[3]);
console.log(obj["3"]);
A

They both access the same property, return “test”

64
Q

How do you determine if there is a property in an object?

A

“key” in object
Returns true or false
The left side of in there must be a property name. That’s usually a quoted string.

If we omit quotes, that means a variable, it should contain the actual name to be tested.

let user = { age: 30 };
let key = "age";

alert(key in user);
or
alert(“age” in user);

65
Q

How do we make a clone of an object?

A

Object.assign(dest, [src1, src2, …])

Example:
let user = {
  name: "John",
  age: 30
};

let clone = Object.assign({}, user);

Keep in mind if a property is an object, you will l have the same problem of copying a reference. To fix that, we should use a cloning loop that examines each value of user[key] and, if it’s an object, then replicate its structure as well. That is called a “deep cloning”.

66
Q
function makeUser() {
  return {
    name: "John",
    ref: this
  };
}

let user = makeUser();

alert( user.ref.name ); // What’s the result?

A

If in strict mode….Error: Cannot read property ‘name’ of undefined

Below works because user.ref() is a method. And the value of this is set to the object before dot .

function makeUser() {
  return {
    name: "John",
    ref() {
      return this;
    }
  };
}

let user = makeUser();

alert( user.ref().name ); // John

67
Q

What kind of type(s) can be object property keys?

A

String and symbol

68
Q

What is a symbol and how do you create one?

A
A “symbol” represents a unique identifier. 
// id is a new symbol
let id = Symbol();
Upon creation, we can give symbol a description (also called a symbol name), mostly useful for debugging purposes:
// id is a symbol with the description "id"
let id = Symbol("id");
69
Q

How can you compare values like ===, but that’ll work with NaN or 0 & -0?

A

Object.is(NaN, NaN) === true

Object.is(0, -0) === false

70
Q

What is the result of this:

console.log( ‘z’ > ‘Z’ );

A

console.log( ‘z’ > ‘Z’ ); //true

71
Q

What is a Map? How is it different than a regular object?

A

Map – is a collection of keyed values.

Map allows keys of any type, including objects. Keys are not converted into strings.

Insertion order is used in Map. The iteration goes in the same order as the values were inserted. Map preserves this order, unlike a regular Object (although we can’t reorder elements or directly get an element by its number).

72
Q

Name some property and methods of Map.

A

new Map() – creates the map.

map. set(key, value) – stores the value by the key.
map. get(key) – returns the value by the key, undefined if key doesn’t exist in map.
map. has(key) – returns true if the key exists, false otherwise.
map. delete(key) – removes the value by the key.
map. clear() – removes everything from the map.
map. size – returns the current element count.

73
Q

What is a Set? Name some property and methods of Set.

A

A Set is a special type collection – “set of values” (without keys), where each value may occur only once.

new Set(iterable) – creates the set, and if an iterable object is provided (usually an array), copies values from it into the set.

set. add(value) – adds a value, returns the set itself.
set. delete(value) – removes the value, returns true if value existed at the moment of the call, otherwise false.
set. has(value) – returns true if the value exists in the set, otherwise false.
set. clear() – removes everything from the set.
set. size – is the elements count.

74
Q

What array methods modify the array itself?

A

sort, reverse, splice

75
Q

How do call() and apply() work and what is the difference?

A

They both allow up to set the value of this ourselves.

call() is a method directly invoked onto a function. We first pass into it a single value to set as the value of this; then we pass in any of the receiving function’s arguments one-by-one, separated by commas.

apply() does the same thing but rather than passing arguments one-by-one, separated by commas – apply() takes the function’s arguments in an array.

Example:
const dave = {
  name: 'Dave'
};
function sayHello(message) {
  console.log(`${message}, ${this.name}. You're looking well today.`);
}
Either:
sayHello.call(dave, 'Hello')
or 
sayHello.apply(dave, ['Hello'])
76
Q
const module = {
  x: 42,
  getX: function() {
    return this.x;
  }
};
const unboundGetX = module.getX; 
const boundGetX = unboundGetX.bind(module); 
const otherGetX = () => module.getX(); 

1) console.log(unboundGetX())
2) console.log(boundGetX())
3) console.log(otherGetX())

Given above, what will these each return?

A
1) The function gets invoked at the global scope. Simply invoking a normal function will set the value of this to the global object
// expected output: undefined
2) Bind makes the module the value of this, allowing it to access x
// expected output: 42
3) This uses an anonymous closure. getX is being used as a method on module, setting this to module.
// expected output: 42
77
Q

How can you check if a property of an object is inherited or not?

A

hasOwnProperty()

Example:
function Phone() {
  this.operatingSystem = 'Android';
}
const myPhone = new Phone();
console.log(myPhone.hasOwnProperty('operatingSystem'));
// true
78
Q

How can you can confirm if a particular object serves as the prototype of another object?

A

isPrototypeOf()

Example:
const rodent = {
  hasTail: true
};
function Mouse() {
  this.favoriteFood = 'cheese';
}
Mouse.prototype = rodent;
const ralph = new Mouse();
console.log(rodent.isPrototypeOf(ralph));
// true
79
Q

What do you get when you use the constructor property on an object?

A

It returns a reference to the constructor function that created that object in the first place.

Example:
function Longboard() {
  this.material = 'bamboo';
}

const board = new Longboard();console.log(board.constructor);

// function Longboard() {
//   this.material = 'bamboo';
// }

If an object was created using literal notation, its constructor is the built-in Object() constructor function!

80
Q

How do you confirm an object’s prototype?

A

Object.getPrototypeOf()

81
Q

Let’s say we want a Child object to inherit from a Parent object. Why shouldn’t we just set Child.prototype = Parent.prototype

A

Objects are passed by reference. This means that since the Child.prototype object and the Parent.prototype object refer to the same object – any changes you make to Child’s prototype will also be made to Parent’s prototype! We don’t want children being able to modify properties of their parents!

On top of all this, no prototype chain will be set up. What if we want an object to inherit from any object we want, not just its prototype?

82
Q

What does instanceof operator do?

A

The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value.

83
Q

What types can a prototype be?

A

A prototype can be either an object or null. Other types are ignored

84
Q

True or false: The for..in loop iterates over both its own and its inherited properties.

A
True!
If want just own properties, could do something like this:
let animal = {
  eats: true
};
let rabbit = {
  jumps: true,
  \_\_proto\_\_: animal
};
for(let prop in rabbit) {
  let isOwn = rabbit.hasOwnProperty(prop);
  if (isOwn) {
    alert(`Our: ${prop}`); // Our: jumps
  } else {
    alert(`Inherited: ${prop}`); // Inherited: eats
  }
}
85
Q

What is a wrapper object? Give an example using a string.

A

Whenever you try to access a property of a string str (a primitive data type with no properties), JavaScript coerces the string value to an object, by new String(str). This object is called a wrapper object.

It inherits all string methods, and is used to resolve the property reference. Once the property has been resolved, the wrapper object is discarded.

Example:
var str = 'hello';

this:
var upper = str.toUpperCase();
console.log(upper); // –> HELLO

...basically translates to:
var upper = (new String(str)).toUpperCase().

The same concept applies to numbers and booleans

86
Q

What is a decorator?

A

Decorator is a wrapper around a function that alters its behavior. The main job is still carried out by the function.
Decorators can be seen as “features” or “aspects” that can be added to a function. We can add one or add many. And all this without changing its code!

87
Q

What is recursion?

A

A programming term that means calling a function from itself. Recursive functions can be used to solve tasks in elegant ways.

88
Q

What is a recursively-defined data structure and give some examples?

A

A data structure that can be defined using itself.

  • The linked list can be defined as a data structure consisting of an object referencing a list (or null).
  • Trees like HTML elements tree or an object made of a company’s departments (and subdepartments) are also naturally recursive: they branch and every branch can have other branches.
89
Q

Describe some benefits and drawbacks of using a linked list vs an array.

A

The “delete element” and “insert element” operations for arrays are expensive. For instance, arr.unshift(obj) operation has to renumber all elements to make room for a new obj, and if the array is big, it takes time. Same with arr.shift(). Push/pop only works at the end.
Linked list have very fast insertion/deletion. Unlike arrays, there’s no mass-renumbering, we can easily rearrange elements.

The main drawback of linked lists is that we can’t easily access an element by its number. In an array that’s easy: arr[n] is a direct reference. But in the list we need to start from the first item and go next N times to get the Nth element.

90
Q

What is a linked list?

A

The linked list element is recursively defined as an object with:

  • value.
  • next property referencing the next linked list element or null if that’s the end.
Example:
let list = {
  value: 1,
  next: {
    value: 2,
    next: {
      value: 3,
      next: {
        value: 4,
        next: null
      }
    }
  }
};
91
Q

What are rest and spread parameters?

A
  • When … is at the end of function parameters, it’s “rest parameters” and gathers the rest of the list of arguments into an array.
  • When … occurs in a function call or alike, it’s called a “spread syntax” and expands an array into a list
92
Q

What is optional chaining?

A

The optional chaining ?. is a safe way to access nested object properties, even if an intermediate property doesn’t exist.

The ?. checks the left part for null/undefined and allows the evaluation to proceed if it’s not so. If not it returns undefined. This allows to safely access nested properties.

The syntax has 3 forms:
obj?.prop – returns obj.prop if obj exists, otherwise undefined.
obj?.[prop] – returns obj[prop] if obj exists, otherwise undefined.
obj.method?.() – calls obj.method() if obj.method exists, otherwise returns undefined.

93
Q

What types of object to primitive conversions are there and name some examples?

A
1) string: when we're doing an operation an an object that expects a string
// output
alert(obj);
// using object as a property key
anotherObj[obj] = 123;
2) number: For an object-to-number conversion, like when we’re doing maths
// explicit conversion
let num = Number(obj);
// maths (except binary plus)
let n = +obj; // unary plus
let delta = date1 - date2;
// less/greater comparison
let greater = user1 > user2;

3) default: when operator not sure what type to expect. With the exception of working with Date object, the default conversion works the same way as number.

// binary plus uses the "default" hint
let total = obj1 + obj2;
// obj == number uses the "default" hint
if (user == 1) { ... };
94
Q

What is a mixin?

A

A mixin is a technique that takes the properties and methods from one object and copies them over to another object. In other words: a mixin is an technique that provides some useful functionality, but is not meant to be added to the prototype chain.

95
Q

What is Object.assign()?

A

Object.assign() is a method that copies an object’s own (non-inherited) properties from one or more source objects into a target object, then returns the updated target object.

Object.assign() does not create and return a new object; it directly modifies then returns the same target object that was passed in! As such, values of existing properties will be overwritten, while properties that don’t exist in the source object will remain intact.

96
Q

What is a factory function and how does it compare to a constructor function?

A

A factory function is a function that returns an object, but isn’t itself a class or constructor. Using a factory function, we can easily create object instances without the complexity of classes and constructors! Factory functions don’t implicate prototypal inheritance and don’t use the ‘new’ operator.

function Basketball(color) {
  return {
    color: color,
    numDots: 35000
  };
}
97
Q

What is a functional mixin?

A

A factory function creates objects. It is invoked as normal function, not with the new operator. Functional mixins take things a bit further by accepting a mixin as an argument, copies properties and methods from the mixin, and returns a new object.

Example:
function CoffeeMaker(object) {
  let needsRefill = false;
  return Object.assign({}, object, {
    pourAll: function () {
      needsRefill = true;
    },
    isEmpty: function () {
      return needsRefill;
    }
  });
}
98
Q

What is a benefit of using the module pattern?

A

It uses closures to create private and public properties of an object, which isn’t provided by JavaScript by default.

When used with an IIFE, it prevents pollution of the global scope (which hinders the chance of variable name collisions) – the IIFE helps prevent access to it’s variables.

let diana = (function () {
  let secretIdentity = 'Diana Prince';
  return {
    introduce: function () {
      console.log(`Hi! I am ${secretIdentity}`);
    }
  };
})();
99
Q

What are the key ingredients to the revealing module pattern?

A

1) An IIFE (wrapper)
2) The module content (variables, methods, objects, etc.)
3) A returned object literal

100
Q

What is a programming paradigm?

A

A strategy for designing and implementing your code. A philosophy, style, or general approach to writing code.

101
Q

What is functional programming?

A

Functional Programming is a programming paradigm that emphasizes using clean functions to create code. This paradigm tries to avoid reassigning values to variables and tries to avoid code that would create unintended side effects. It keeps the processing within functions.

102
Q

What is a pure function?

A

A function that will always return the same output if given the same input, and which has no side effects.

103
Q

What is a side effect?

A

An effect on your overall program from running a function, that did not come from the return statement of that function.

104
Q

What is an immutable value?

A

Unchanging. Immutable values are ones which, once declared, cannot be changed.

105
Q

What type of language is JavaScript?

A

JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. JavaScript is a prototype-based, multi-paradigm, single-threaded, dynamic language, supporting object-oriented, imperative, and declarative (e.g. functional programming) styles.

As a multi-paradigm language, JavaScript supports event-driven, functional, and imperative programming styles. It has application programming interfaces (APIs) for working with text, dates, regular expressions, standard data structures, and the Document Object Model (DOM).

106
Q

What are the functional array methods?

A

map, filter, and reduce.

107
Q

What is the map array method?

A

The map method performs an action on every item in an array, but creates a new array to store the results.

array.map((currentValue, index, arr) => { })

108
Q

What does this return?

console. log( ‘01’ == 1 );
console. log( true == 1 )

A

True. When comparing values of different types, JavaScript converts the values to numbers.
True. For boolean values, true becomes 1.

109
Q

What is the difference between == and ===?

A

Operands of different types are converted to numbers by the equality operator ==.

A strict equality operator === checks the equality without type conversion.

110
Q

What array method allows you to undo array nesting?

A

flat()

Example:
var nestedArr = [1, 2, [3, 4, [5, 6]]];
nestedArr.flat();
console.log(nestedArr)
// expected output: [1, 2, 3, 4, [5, 6]]

var moreNested = [1, 2, [3, 4, [5, 6]]];
moreNested.flat(2);
console.log(moreNested)
// expected output: [1, 2, 3, 4, 5, 6]

111
Q

What does the find array method do?

A

The find() method is an Array.prototype (aka built-in) method which takes in a callback function and calls that function for every item it iterates over inside of the array it is bound to.

When it finds a match (in other words, the callback function returns true), the method returns that particular array item and immediately breaks the loop. So the find() method returns the first element inside an array which satisfies the callback function.

Syntax:
Arrow function- find((element, index, array) => { /* … */ } )

Inline call- find(function(element, index, array) { /* … */ }, thisArg)
With inline call, can have parameter “thisArg”, which is an object to use as this in callback function. (Can’t use in arrow function because it doesn’t bind their own this

112
Q

What does this includes method do?

A

includes is most useful when are looking for the existence of a specific value. All you have to do is provide the value you are looking for, and includes will return true if it finds it and false if it does not.

includes(searchElement, fromIndex)

113
Q

Reduce

A

Don’t forget to return acc in the reduce method!

114
Q

What is a high order function?

A
  • returns a function

- receives a function as an argument

115
Q

How do you destructure an object?
How do you assign a property to a variable with another name?
How do you set a default value?

A

Assign a property with a colon. Add default value with an equality sign.

let options = {
  title: "Menu"
};

let {width: w = 100, height: h = 200, title} = options;

alert(title); // Menu
alert(w); // 100
alert(h); // 200

116
Q

What is the difference between for..in and for..of?

A

Both for..of and for..in statements iterate over lists; the values iterated on are different though, for..in returns a list of keys on the object being iterated, whereas for..of returns a list of values of the numeric properties of the object being iterated.

let list = [4, 5, 6];

for (let i in list) {
console.log(i); // “0”, “1”, “2”,
}

for (let i of list) {
console.log(i); // “4”, “5”, “6”
}

Another distinction is that for..in operates on any object; it serves as a way to inspect properties on this object. for..of on the other hand, is mainly interested in values of iterable objects. Built-in objects like Map and Set implement Symbol.iterator property allowing access to stored values.

let pets = new Set(["Cat", "Dog", "Hamster"]);
pets["species"] = "mammals";

for (let pet in pets) {
console.log(pet); // “species”
}

for (let pet of pets) {
console.log(pet); // “Cat”, “Dog”, “Hamster”
}

117
Q

a()

function a() {
console.log('hi')
}
function a() {
console.log('bye')
}
A

‘bye’

With variables, they’re partially hoisted so we have undefined to that variable.

However….

during the hoisting phase, we fully hoist function declarations!

118
Q

What logs?

var favoriteFood = “grapes”;

var foodThoughts = function () {
     console.log(favoriteFood);
     var favoriteFood = "sushi"
     console.log(favoriteFood);
}

foodThoughts()

A

undefined
sushi

Hoisting on every execution context. Every time we run a function, a new execution context get created and we have to go through the creation phase and execution phase again.

favoriteFood gets hoisted within the foodThoughts function, so when the first console.log happens, favoriteFood within that function is initialized but undefined.

If we remove the var from the function and simply had favoriteFood = “sushi”, then the first console.log would be grapes.