fundamentals Flashcards

1
Q

((false && undefined) || (false || undefined));

A

undefined

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

What does the code return?
[…Array(3)]

A

[undefined, undefined, undefined]

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

Insert an array into another array with spread syntax

let foo = [1, 2, 3]
// code here
bar; // => [1, 2, 3, 4, 5, 6, 1, 2, 3]

A

let bar = […foo, 4, 5, 6, …foo];

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

Which operator converts the non string to a string if the other operand is a string?

A

+

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

What does the code do?

Array.prototype.splice(0, 1) ;

A

It removes 1 element from energy, starting at index 0

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

What does this return?
‘4’ + 3

A

3 is coerced to the string ‘3’, so the result is ‘43’

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

What does this return?
‘fava’.charCodeAt(2)

A

The number of ‘v’ in the unicode: 118

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

undefined >= 1

A

// false – becomes NaN >= 1

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

What does this return?
1 + true

A

true is coerced to the number 1, so the result is 2

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

What happens here?
[1, 2] * 2;

A

[1, 2] becomes ‘1,2’, * 2 then NaN * 2 => NaN

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

NaN != NaN

A

true

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

When should you use try/catch/finally ?

A

A built in function or method can throw an error and you need to catch it

A simple guard clause is impractical

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

Operator after operand: (a++)
a = 1;
What is:
b = a++;

A

equivalent to “b = a; a++;”. so now b is 1 and a is 2

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

null == undefined

A

true

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

Braket notation is?

A

An operator. Not a method

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

‘11’ > 9

A

// true – ‘11’ is coerced to 11

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

Does javascript interpret a statement starting with a curly brace as an object literal?

A

No. it thinks it’s a block. Use parenthesis to force it to take it as an object literal

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

What does this return?
const str1 = ‘strunz’;
str1.endsWith(‘u’, 5);

A

false

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

How do you count all of the properties in an array, as opposed to only the indexed values?

A

Object.keys(array).length

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

Describe a mental model for how closures work

A

At the time of the function definition, javascript collects all the variable names that are in the function scope and places them in an ‘envelope’. This is then assigned to the function object. These variable names are pointers to the variable, as opposed to the value the variables point to. This is so that javascript can be aware of any reassignments the variables may have

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

What does this return? Why?
‘50’ < ‘6’

A

true. ‘5’ < ‘6’
There is no coercion if same type

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

Merge objects with spread syntax

let foo = { qux: 1, baz: 2 };
let xyz = { baz: 3, sup: 4 };
// code here
obj; // => { qux: 1, baz: 3, sup: 4 }

A

let obj = { …foo, …xyz };

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

Create a shallow clone of an array with spread syntax

let foo = [1, 2, 3];
//…. code here
foo.pop();

console.log(foo); // [1, 2]
console.log(bar); // [1, 2, 3]

A

let bar = […foo];

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

How to you return 2 to the power of 3?

A

Math.pow(2, 3)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
('a' && (false || undefined) && '');
undefined
26
How to check if a value is an integer?
Number.isInteger(value) => true or false
27
Name four side effects?
reading from the keyboard (prompt() generating random numbers accessing date and time If a function can raise an exception and doesn't catch and handle it, it has a side effect:
28
undefined == null
true
29
How do you make a quantifier lazy?
Add a '?' to the quantifier. Ex. *?
30
Operator before operand: (++a) a = 1 c = ++a;
equivalent to "++a; c = a;". so now c is 2 and a is 2
31
What does the code log and why? console.log(greeting); let greeting = 'Hello world!';
ReferenceError: Cannot access 'greeting' before initialization; Variables declared with let and const are hoisted but not initialised. They are said to live in the TEMPORAL DEAD ZONE until they are initialised to a value
32
What is a type error?
Trying to access a value on a property that doesn't have any such as null. When you call an method on an object you are accessing a value (the method) on that property
33
What does the regex specify? p{3}
Exactly 3 occurrences of p
34
Perform Object Destructuring on the following code: let obj = { foo: "foo", bar: "bar", qux: 42, }; that does the same as: let foo = obj.foo; let bar = obj.bar; let qux = obj.qux;
let { foo, bar, qux } = obj;
35
What does the code log and why? console.log(greeting); var greeting = 'Hello world!';
undefined. var is hoisted but nothing is assigned to it. It's like it was written like this: var greeting; console.log(greeting); greeting = 'Hello world!';
36
Statements vs expressions:
Unlike expressions, statements don't resolve to a value: let yay; they control the execution of a program: if else statements, for loops etc. Statements help you do something as opposed to giving a value
37
What does the code log? let ocean = {}; let prefix = 'Indian'; ocean.prefix = 'Pacific'; console.log(ocean);
{ prefix: 'Pacific' }
38
What are the associations between a name (or key) and a value in an object?
properties
39
Can Array.prototype.slice be passed a negative index as an argument to extract elements from the end of an array?
Yes: ['f', 'a', 'v', 'a'].slice(-2, -1); => ["v"] ['f', 'a', 'v', 'a'].slice(-2); => ["v", "a"] ['f', 'a', 'v', 'a'].slice(-2)[0]; => 'v'
40
What does this log? let person = { title: 'Duke', name: 'Nukem', age: 33 }; console.log(Object.entries(person));
[['title', 'Duke'], ['name', 'Nukem'], ['age', 33]] An array of sub arrays
41
What does this return? 0 == false //
true -- becomes 0 == 0
42
What is an assignment?
a stand alone expression that assigns a new value to a variable
43
What does this return? const str1 = 'strunz'; str1.startsWith('u', 4);
false
44
11 > '9'
// true -- '9' is coerced to 9
45
slice() vs splice()
slice() return a portion of an array. splice() can modify an array; delete items, insert them or replace them splice(start, deleteCount, item1, item2, itemN)
46
Atom shortcuts: Highlights all instances of the same word
command control g
47
What does the regex specify? p{5,}
5 or more occurrences of p
48
how do you get the unique values from an array? let array = [1, 1, 2, 3, 3]
[...new Set(array)] => [1, 2, 3]
49
What does this return? 1 + undefined
NaN
50
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']; console.log(animals.splice(0, 2)); console.log(animals);
["ant", "bison"] // the deleted items ["camel", "duck", "elephant"] // the mutated array
51
Which data type does Number.prototype.toFixed() return?
A string
52
Return a random integer between 0 and 3
Math.floor(Math.random() * 4);
53
What does the code return? [...Array(3)].fill(2)
[2, 2, 2]
54
JavaScript style guides usually recommend using which notation when possible.
dot notation. as opposed to bracket
55
What is an initialiser?
Looks like assignment but it's different in terminology; it's the expression to the right of '=' in a variable declaration. ex: let number = 35;
56
What is this equal to? [ ...unused, ...washed ]
unused.concat(washed);
57
((false || undefined) || (false && undefined));
false
58
Why is it a bad idea to run arithmetic operators on arrays?
Besides producing useless results they run without producing a warning!
59
What specific examples of code can you think of that strict mode doesn't allow?
Cannot create undeclared variables in functions so that they become global variables Cannot start an integer with 0. Apart from 0 itself
60
Objects are containers for two things:
data (properties) and behaviour (methods)
61
undefined == ''
false
62
What does typeof null return and why?
Object. This is a historic bug. It's too late to change it
63
How to get a value from an ascii code?
String.fromCharCode(68)
64
How does array.find() work?
It returns the first value in the array that results to true to the provided callback function: const array1 = [5, 12, 8, 130, 44]; const found = array1.find(element => element > 10); console.log(found); // expected output: 12
65
true > null
// true -- becomes 1 > 0
66
What does this return? 'a'.localeCompare('b');
-1
67
Under which conditions should you use the try, catch blocks?
1 - The built in function or method might throw an error and you need to handle it 2 - A simple guard cause is impossible or impractical
68
Destructure the array but only 1 and 7 let bar = [1, 2, 3, 4, 5, 6, 7]; As if you were writing; let first = bar[0]; let seven = bar[6];
let [ first, , , , , , seventh ] = bar;
69
What does this return? const str1 = 'strunz'; str1.startsWith('u', 3);
true
70
What does this return? '' == false
true -- becomes '' == 0, then 0 == 0
71
What is a type error?
When you call an inexistent method on an object or primitive.
72
What does the code return? [...Array(3)].fill(2)
[2, 2, 2]
73
What is a reference error?
When you attempt to reference a variable or function that doesn't exist
74
How would a regex that would match either dog, cat or rat look like and what is the type of regex called?
(cat|dog|rat) it is called 'alternation'
75
Create a clone of an object with spread syntax let foo = { qux: 1, baz: 2 }; // code here console.log(bar); // { qux: 1, baz: 2 } console.log(foo === bar); // false -- bar is a new object
let bar = { ...foo };
76
123 <= 'a'
// also false
77
What does this return? true == '1'
true -- 1 == 1
78
Describe four (4) ways to create a date object:
new Date(); new Date(value); new Date(dateString); // new Date('December 17, 1995 03:24:00') or // new Date('1995-12-17T03:24:00') new Date(year, month[, date[, hours[, minutes[, seconds[, milliseconds]]]]]); // new Date(1976, 4, other optional args); Passing in the date object directly also works (e.g., new Date(today)). However, this employs implicit coercion which we don't recommend. Using the Date.prototype.getTime method makes it clear what is going on.
79
123 > 'a'
// false -- 'a' is coerced to NaN; any comparison with NaN is false
80
let foo = false;
undefined --- statements always return undefined
81
What is an expression?
any code that resolves to a value
82
What is an element of an array?
a value who has a non negative integer as it's key (property name)
83
undefined === null
false
84
How to get a value from an ascii code?
String.fromCharCode(68)
85
What does the regex specify? p{3, 7}
3 to 7 occurrences of p
86
How do non strict equality operators == coerce the following: '23' == 23
It coerce the string to be a number 23 === 23 => true
87
What does the code do? Array.from('foo');
["f", "o", "o"]
88
How do you add two decimal points to a value?
value.toFixed(2);
89
undefined == false
false
90
What does the code log? let guess = false ? 1 : 2; console.log(guess);
2. Guess is false so it has the second argument passed to it
91
What is the regex for the anchor at the end of a string?
$
92
Use rest syntax to desctructure the following: let foo = [1, 2, 3, 4]; console.log(bar); // 1 console.log(qux); // [2, 3, 4]
let [ bar, ...qux ] = foo;
93
What does the code log? let guess = true ? 1 : 2; console.log(guess);
1. Guess is true so the first argument is passed to it
94
What does this return? const str1 = 'strunz'; str1.endsWith('u', 4);
true
95
Name three changes strict code brings
Eliminates silent errors by throwing an exception Prevents code than can inhibit javascript from optimising a program later on so that it runs faster Prevents using names and syntax that may clash with future versions
96
Use Array destructuring for this code: let foo = [1, 2, 3]; let first = foo[0]; let second = foo[1]; let third = foo[2];
let [ first, second, third ] = foo;
97
What does this return? let friends = ['Bob', 'Josie', 'Sam']; let enemies = friends; console.log(friends === enemies);
true
98
What does this return? 'fava'.charAt(2);
'v'
99
How does hoisting work differently depending on the type of declaration?
For a function declaration both the function name and function body get hoisted. For variables only the name does. var is initialised to undefined. let and const are said to be in a TEMPORAL DEAD ZONE until initialised and inaccessible until then
100
What does this return? why? '123' * 3
369 all arithmetic operators other than + convert operands to numbers
101
What does this return? '0' == false (two conversions)
true -- becomes '0' == 0, then 0 == 0
102
What does this return? let friends = ['Bob', 'Josie', 'Sam']; let enemies = ['Bob', 'Josie', 'Sam']; console.log(friends[0] === enemies[0]);
true
103
What does this return? null + true
1
104
What is a pragma?
A language construct that tells the compiler to process the code in a different way. It's not part of the language
105
Closures are:
A lexical, rather than a runtime feature
106
Which are the meta characters inside a character class?
^ \ - [ ]
107
When is a property name an array index?
when it's a non negative integer; (their values are called elements) any other property name is not an array index and its associated value is not called element. Array.prototype.indexOf returns -1 if the value it is passed is not an element of the array,
108
Can i code [1, 2] + [3] and get [1, 2, 3] ?
no. you'll get '1, 23' use .concat() instead; [1, 2].concat([3]) // [1, 2, 3]
109
What does this return? 'hello'.charAt(1);
"e"
110
What is a closure?
a combination of a function and it's lexical environment
111
How do you prevent a Type Error from being thrown when a reduce() method encounters an empty array? ex: [].reduce(reducer);
[].reduce(reducer, 0) the 0 provided will be the default value assigned to the accumulator
112
What happens when the + operator has two operands and one is an object? [1, 2] + 4
they are both converted to strings '1,24'
113
How do you remove the first property from foo? let foo = { a: 'hello', b: 'world', };
delete foo.a; foo; // { b: "world" }
114
What is return value of statements?
The return value of statements in JavaScript is undefined, and the return value of an expression with an operator is operator dependent. For the assignment (=) operator, the return value is the value assigned to the variable on the left side.
115
Does the closure include all the existing variables within the scope of the function?
no. only the ones that the function needs
116
null <= false
// true -- becomes 0 <= 0
117
What's the difference between String.substr() and String.substring() ?
The substr() method extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters. The substring() method returns the part of the string between the start and end indexes, or to the end of the string
118
What is the technical name for ...theArgs? function sum(...theArgs) { //... }
Rest parameter
119
What is the difference between String() and toString() ?
String() can convert all types, including null and undefined, while toString() raises an exception. Also String() always returns a string. Individual objects could override toString() though
120
How do you use BigInt?
append an n to the number
121
How to you convert a number, ex: 1234 into binary?
let num = 1234; num.toString(2);
122
What happens here? [1] * 2;
The operation becomes '1' * 2, then the '1' is converted to 1. So we get 1 * 2 => 2
123
What does this log? const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']; console.log(animals.splice(0)); console.log(animals);
['ant', 'bison', 'camel', 'duck', 'elephant']; // the deleted items [] // the mutated array
124
What is an initializer?
the expression to the right of the = in a variable declaration
125
What happens when the + operator has two operands and neither are strings or object? true + false
they are converted into numbers 1 + 0 => 1
126
What does this return? 5 + '41'
'541'
127
true > false
// true -- also becomes 1 > 0
128
How do you create an array from the 'arguments' pseudo array?
let args = Array.prototype.slice.call(arguments);
129
Concatenate arrays with spread syntax let foo = [1, 2, 3]; let bar = [4, 5, 6]; // code here qux; // => [1, 2, 3, 4, 5, 6]
let qux = [...foo, ...bar];
130
What does this return? true == 'true'
false -- 1 == NaN
131
Where should I not declare functions?
In non function blocks like "if else" statements. You should instead use arrow functions or function expressions
132
NaN == 0
false
133
What does it mean for javascript to be weakly typed?
You don't have to use type specific variables to store values, like for instance in C: int i = 7
134
What is the result of these comparisons: let friends = ['Bob', 'Josie', 'Sam']; let enemies = ['Bob', 'Josie', 'Sam']; friends == enemies; friends === enemies; [] == []; [] === [];
false false false false they are all different objects. arrays are only equal when they are the same object.
135
null == null
true
136
What does this return? 42 == true
false -- becomes 42 == 1
137
What makes a pure function?
Have no side effects. Given the same set of arguments, the function always returns the same value during the function's lifetime. This rule implies that the return value of a pure function depends solely on its arguments.
138
NaN === NaN
// false -- even with the strict operator
139
NaN == NaN
false
140
What will happen with this code and why? let counter = 5; let rate = 3; function counter(count) { // ... } console.log('The total value is ' + String(counter * rate));
It will raise an exception; A function declaration creates a variable with the same name as the function name. If the variables had been declared with var it would have worked fine
141
What does this return? const str1 = 'strunz'; str1.startsWith('u');
false
142
What are higher order functions?
They are just normal functions with the extra ability to receive functions as arguments and also return them
143
Why does the code result in an error? let boxNumber = 356.toString(); // syntax error!
Javascript interprets a period after a number as a decimal point, not as a method separator. Do this instead: 356..toString(); or (356).toString();
144
What does this log? const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']; console.log(animals.splice()); console.log(animals);
[] // the deleted items ['ant', 'bison', 'camel', 'duck', 'elephant'] // the 'mutated' array. not really mutated in this case
145
What does the regex cover: \w
\w matches all letters, number and underscore
146
null == false
false
147
How does this work: let state = 'Mississippi'; state.substring(6, 3);
// "sis", starting at index 3 and ending at the one before index 6. The order of start or end doesn't matter. The start is the smaller of the two. The last index isn't included in the substring. The index at one less than the index supplied is
148
What does the code return? [...Array(3)].fill();
[undefined, undefined, undefined]
149
What does the code log and why? function myFunction() { let a = 1; if (true) { console.log(a); let a = 2; console.log(a); } } myFunction();
ReferenceError: Cannot access 'a' before initialization. the let a = 2 inside the if block is hoisted but uninitialized. console.log(a) can't access it and it also shadows the let a = 1
150
undefined == undefined
true
151
What is an array property name?
It's a non negative index of an array. Values assigned to them are called elements
152
Which are the primitive types?
Strings, numbers, booleans, undefined and null
153
Can you use \b or \B word and non word boundaries in character classes?
No. \b means backspace in a character class
154
What is the difference between slice() and substring()
slice() is for arrays while substring() if for strings. they return a new array or string
155
How and where do you enable strict mode?
"use strict"; Can be used at the global or at the function level Can't be used inside a block. Top of the code or top of the function only
156
Can you use arrow functions as methods?
Better not. They have subtle behaviour that makes them unsuitable. Will learn more later. It is safe to use arrow functions in the body of a method; just don't use them to define the actual method.
157
How do you make " " three times bigger?
" ".repeat(3)
158
((false && undefined) || 'a' || '');
'a'
159
What does it mean for javascript to be dinamically typed?
The value of any variable can be changed for another value of a different type
160
What does this return? +'1'
the number 1. Prepending a string with + turns it into a number if possible or NaN if not +'1a' would return NaN
161
Make a RegExp to include word boundaries
let regex = RegExp(`\\b${uniqueString}\\b`, 'g');
162
How do non strict equality operators == coerce the following: 0 == '\n'
It coerce the string to be a number 0 === 0 => true
163
How do you represent a non decimal character in regex?
\D
164
What data type are object property names?
Strings. When we omit the quotes around a property name javascript converts it into a string anyways so that an entry like: true: 'whatever' is converted to 'true': 'whatever'
165
What does the code return? Array(3)
[empty × 3]
166
Return a random integer between 14 and 17
Math.floor(Math.random() * 4 + 14);
167
What is this equal to? [ ...unused, ...washed ]
unused.concat(washed)
168
How else could you write array.join('') ?
array.join``
169
What does the code log? console.log(Array.from('foo'))
Array ["f", "o", "o"]
170
What does the code log? console.log(Array.from([1, 2, 3], x => x + x))
Array [2, 4, 6]
171
What does the code log? Array.from(new Set('abc'));
["a", "b", "c"]
172
What does the code log? [...'abc']
["a", "b", "c"]
173
What is encapsulation?
The grouping of related variables and functions that operate on them into objects. Reduces the number of parameters the function takes. Avoids functions being scattered throughout the program. This is problematic because interdependence between functions can lead to bugs or code possibly breaking if change to one function affects others
174
What problem does OOP solve?
Reduces the interdependence of functions. Sectioning off chunks of code has many benefits: reduced the impact of change to any one function, simplifies code, removes parameters from functions
175
What is abstraction?
The hiding of properties and methods from outside the object. This has two benefits: - It simplifies the object's use and understanding - It minimises the impact of change if we decide to make changes to the private, or hidden, methods those changes won't affect the code outside of the object
176
What is polymorphism?
Two objects of different types can respond differently to the same method call. Remove a bunch of if else statements
177
How would you pass a function called, say, fullName(), to the following forEach() method? function rollCall(people) { // code here }
people.forEach(fullName); note that's just a variable whose value is a function. We don't add parenthesis to call the function. Each element in the people array will be passed as an argument to the function: fullName(element);
178
What happens when a function is invoked using the () syntax?
A context is assigned to the function. Every function has a context assigned at execution time.
179
What does the global window object do?
Provides variables and functions that are available throughout the program.
180
What happens if you declare a global variable with var or a function?
They become a property of the window object. It doesn't work with let and const. you have to use dot notation as with any other object: window.example = 'whatever';
181
What is the 'this' keyword?
It's a synonym for the execution context. It's the object that is housing the property.
182
What does this return? [1, 2, 3].splice(undefined, 1);
1 It removes the first element and mutates the array => [2, 3];
183
What does this return? [1, 2, 3].splice(-1, 1);
3 It removes the first element from the end and mutates the array => [1, 2];
184
Is -1 truthy?
It is. All negative numbers are truthy.
185
What is the value of b? Why? let a = 'fava'; let b = a; a = 'banana'; console.log(b);
'fava' With primitive values it's not the reference that's passed but the value itself. So when b is created to be equal to a there will be two 'fava' in memory. Each variable points to a different space in memory. The two items look the same but they are different things. This is an example of "pass by value".
186
What is stored on the stack?
Primitive values and references to objects. The objects references point to are stored in the heap. If there are several references to an object they will all point to the same object, which means that any one reference can mutate the object and other references will see the changes too.
187
Video way to copy an object...
let a = {name: 'dan'}; let b = Object.assign({}, a); a.name = 'fava'; console.log(a.name); // fava console.log(b.name); // dan
188
What is logged by the code? let a = 10; let obj = { a } let newObj = obj; newObj.a += 10; console.log(obj.a); console.log(a);
20 10
189
What is logged by the code? let a = 10; let obj = { a } obj.a += 10; console.log(obj.a); console.log(a);
20 10
190
What is logged by the code? let a = 10; let obj = { a } let newObj = obj; newObj.a += 10; console.log(obj.a); console.log(newObj.a);
20 20
191
How would you call this type of function? function makeCar(rate, braking) { return { speed: 0, braking, rate, accelerate() { this.speed += this.rate; }, brake() { this.speed -= this.braking; if (this.speed < 0) { this.speed = 0; } }, }; }
Object factory
192
How does OOP work as opposed to procedural programming?
OOP uses objects as the building blocks of a program as opposed to local variables and functions.
193
The object oriented code makes which questions easier to answer?
- What are the important concepts in the program? - What are the properties of an object? - How do we create an object? - What operations can I perform on an object? - Where should we add new properties and methods?
194
What are the three main benefits of OOP?
- We organize related data and code together. - It's useful when a program needs more than one instance of something. - It becomes more useful as the codebase size increases.
195
What characterises a first class function?
- we can add them to objects - execute them in the context of those objects - remove them from their objects - pass them to other functions and run them in entirely different contexts - First-class Functions initially have no context; they receive one when the program executes them.
196
What does javascript create when it starts running?
The global object. This is used as the implicit execution context. In the browser this is the window object
197
What is the difference between declaring a variable with var and not declaring it, in the context of the global object?
You can delete variables that you don't declare but not the ones you do! If you declare it, you keep it! Function declarations work the same as var variables
198
Is the global object always window?
NO. Only in the browsers. In Node it's 'object'. Also, Node introduces an additional "module" scope; variables declared in the outermost scope are placed in the module and not available in the global object. Undeclared variables, on the other hand, are!
199
Are the `this` binding rules similar to closures and variable scope?
No. It's not determined by the lexical code but by how the function is invoked
200
What is another name for the implicit function execution context
Implicit binding for functions
201
Does `bind` execute a function?
No. It creates a new one permanently bound to the specified execution context
202
What will the code below log to console? let obj = { message: 'JavaScript', }; function foo() { console.log(this.message); } foo.bind(obj);
Nothing. Unlike call and apply, bind doesn't invoke the receiver function. Rather, it returns a new function that is permanently bound to the context argument.
203
What does this log? let hobbies = { a: 'fencing', b: 'mincing', foo() { return this.a + ' and ' + this.b; }, }; let bar = hobbies.foo(); console.log(bar);
fencing and mincing
204
What does this log? let hobbies = { a: 'fencing', b: 'mincing', foo() { return this.a + ' and ' + this.b; }, }; let bar = hobbies.foo; console.log(bar());
undefined and undefined
205
What is logged here? let obj = { a: 'hello', b: 'world', foo() { function bar() { console.log(this.a + ' ' + this.b); } bar(); }, }; obj.foo();
undefined undefined Even though foo executes within the obj context, the call to bar on line 9 does not provide an explicit context, which means that JavaScript binds the global object to the function. As a result, this on line 6 is the global object, not obj.
206
Can you chain bind() to a function delcaration?
No. It must be a function expression let bar = function() { console.log(this.a + ' ' + this.b); }.bind(this); Chaining it to a function declaration would result in an error
207
There are 4 workarounds to make sure the bar() function doesn't lose it's context. What are they? let obj = { a: 'hello', b: 'world', foo() { function bar() { console.log(this.a + ' ' + this.b); } bar(); }, }; obj.foo() // undefined undefined
1 - let obj = { a: 'hello', b: 'world', foo() { function bar() { console.log(this.a + ' ' + this.b); } bar.call(obj); }, }; obj.foo() 2 - error here. Can’t add bind to function declarations let obj = { a: 'hello', b: 'world', foo() { let self = this; function bar() { console.log(self.a + ' ' + self.b); } bar(); }, }; obj.foo() 3 - let obj = { a: 'hello', b: 'world', foo() { let bar = function() { console.log(this.a + ' ' + this.b); }.bind(obj); bar(); }, }; obj.foo() 4 - let obj = { a: 'hello', b: 'world', foo() { let bar = () => console.log(this.a + ' ' + this.b); bar(); }, }; obj.foo()
208
We can fix the below bug with the previously explored solutions. What is an easy additional way? let obj = { a: 'hello', b: 'world', foo() { [1, 2, 3].forEach(function(number) { console.log(String(number) + ' ' + this.a + ' ' + this.b); }); }, }; obj.foo(); // undefined undefined
let obj = { a: 'hello', b: 'world', foo() { [1, 2, 3].forEach(function(number) { console.log(String(number) + ' ' + this.a + ' ' + this.b); }, this); }, }; obj.foo(); We supply a second argument, this, to the forEach function. This argument is the context. Array.prototype.map, Array.prototype.every, and Array.prototype.some also takes an optional thisArg argument.
209
Do arrow functions have a this binding?
No. Arrow functions do not have a `this` binding. Instead of `this` being dependent on the location of the function invocation, JavaScript resolves it by looking at the enclosing scopes.
210
Does a function passed in as an argument to another function keeps its execution context?
No. Inner functions lose the outer object as context. It would as an arrow function, though.
211
Define 'this'
The current execution context of a function
212
How does strict mode affect 'this' in function calls?
Without strict mode 'this' refers to the window object. In strict mode it's undefined
213
Remember...
All JavaScript code executes within a context. The top-level context in a web browser is the window object. All global methods and Objects (such as parseInt or Math) are properties of this object. In Node, the top-level context is called global. However, be aware that Node has some peculiarities that cause it to behave differently from browsers.
214
The value of this changes based on ...
...how you invoke a function, not how you define it.
215
JavaScript has first-class functions which have the three following characteristics:
- You can add them to objects and execute them in the respective object's contexts. - You can remove them from their objects, pass them around, and execute them in entirely different contexts. - They're initially unbound, but dynamically bound to a context object at execution time.
216
Does this method invocation use implicit or explicit execution context? let obj = { foo() {} }; function bar() {} obj.foo();
Implicit
217
What does this log? function helloFactory() { return function() { console.log('hi'); }; } console.log(helloFactory());
The return function: function() { console.log('hi'); };
218
How would you invoke the function so that the inner return function is executed immediately? What does this log? function helloFactory() { return function() { console.log('hi'); }; } console.log(helloFactory());
helloFactory()();
219
What does it mean that a language has first-class functions?
It means that the language treats functions as values – that you can assign a function into a variable, pass it around etc. First class functions are functions that are treated like an object (or are assignable to a variable)
220
What's the trade off of keeping data private?
Making data private can make it harder to extend the code. You may not be able to add a function outside of the object to manipulate private data. You have to update the object itself by adding a method.
221
When does the program garbage collect primitives and objects?
When the program has no more references to them
222
In what way are function declarations different from function expressions?
As an expression it means that there is a value returned — the function
223
Is garbage collection in JavaScript is responsible for memory deallocation?
Yes
224
What will this log? const person = { firstName: 'Rick ', lastName: 'Sanchez', fullName: this.firstName + this.lastName, }; console.log(person.fullName);
NaN. Anywhere outside a function, the keyword this is bound to the global object. If the keyword is used inside a function, then its value depends on how the function was invoked.
225
What is the purpose of this code? let args = Array.prototype.slice.call(arguments);
It generates a real array from the quasi array 'arguments'. Here we borrow the slice() method from the Array global object and with call(arguments) we give the 'arguments' context to the method. args will now be a real array whose elements are the elements in 'arguments';
226
What does the object property __proto__ do?
It references Object prototype and it keeps looking up in the hierarchy of objects for a property it doesn't find in the current.
227
What are 2 disadvantages of factory functions?
- Every object created with the factory function has a full copy of all the methods, which can be redundant. - There isn't a way for us to inspect an object and know whether we created it from a factory function. This makes it difficult to identify whether an object is of a specific "type."
228
How do you crate a deep clone of let arr = [1, 2, 3] ?
let fava = Array.prototype.slice.call(arr); fava.pop(); console.log(fava); // [1, 2] console.log(arr); // [1, 2, 3]
229
Does the prototype property exist in common object?
No. It's only found in functions. But the __proto__ property will point to the parent object: let arr = [1, 2, 3]; let fava = Object.create(arr); console.log(fava.__proto__); // [1, 2, 3]
230
What does the new keyword do for us in function ParentExample(name, points) { // some code } let example = new Object.create(parentExample) ?
- It creates a new object and sets the __proto__ property in example to point to the prototype property of ParentExample, which itself refers to an object. - It automatically returns the new object.
231
What 4 things happen when we call a function with the new operator?
- A new object is created - 'this' is set to the new object - The function is run - The new object is returned (or if not returned explicitly the 'this' keyword is returned instead.
232
What is logged when inner() runs? Why? let numbers = { a: 1, b: 2, add() { console.log(this.a + this.b); // 3 function inner() { console.log(this.a + this.b); } inner(); } }; numbers.add()
Uncaught TypeError: Cannot read property 'a' of undefined. The inner function does not inherit the 'this' from the add() method. inner() is a function invocation, not a method. As such, it's implicitly assigned the global object as execution context (or undefined in strict mode).
233
Will assigning the myCat.logInfo method as an argument to the function work? function Animal(type) { this.type = type; this.logInfo = function() { console.log(this.type); } } var myCat = new Animal('Cat'); setTimeout(myCat.logInfo, 1000);
No. setTimout(myCat.logInfo); // is equivalent to: var extractedLogInfo = myCat.logInfo; setTimout(extractedLogInfo); This is a solution: setTimeout(myCat.logInfo.bind(myCat), 1000);
234
Can a constructor be called without parenthesis if there are no arguments?
Yes, the parenthesis pair can be omitted: new FunctionName
235
What is another way to write this = Object.create(Fava.prototype); ?
Object.setPrototype(this, Fava.prototype);
236
What are the 5 things that happen when we create an object with a constructor function using the `new` keyword?
- A new object is created - The `this` keyword of the creator function is set to point to the new object - The value of the function prototype property is the object that the new object inherits from - It invokes the function - It returns the new object unless another object is returned explicitly
237
What objects implicitly get a prototype property in Javascript?
Every Function object will automatically get a prototype property which has an object as a value. This object will contain the constructor property. This will then point to the function itself
238
What should methods defined on the prototype always do?
Return the context object!!
239
What are three caveats about using classes?
All code in class executes in strict mode. Unlike function declarations, class declarations are not hoisted. Invoking the class constructor without the new keyword raises an error.
240
What will this log? console.log(typeof Object)
function! Objects, Arrays and Functions are functions, since each of their creator property points to Function. Function made them so they are instances of function
241
What does this do? Object.create(obj)
It creates a new object and sets it's dunder proto to point to obj
242
In node, where are variables declared with var or let stored? var foo = 'foo'
In the module scope
243
In node, where are variables declared without stored? foo = 'foo'
In the global object.
244
What happens to a function's context when the function is used as an argument, like, say, a callback function?
The context is lost and it's implicitly set to the global object. Undefined on strict mode. Unless they are arrow function that is. The same happens to methods!! Passed in as arguments they lose their original binding
245
What do the following all point to? function fava() {} Array.prototype.__proto__ Function.prototype.__proto__ fava.prototype.__proto__
Object.prototype
246
What is 'this' in arrow functions?
'this' is the enclosing context where the arrow function is defined.
247
Syntax errors occur during which phase?
Creation. As opposed to the execution phase. let foo = "hello"; function foo() { console.log("hello"); } At creation, when the engine reaches the function it's aware that foo was already declared with let. So it raises an error
248
const person = { first: 'R ', last: 'S', full: this.first + this.last, }; console.log(person.full);
If you said it logs NaN, you're correct. It is tempting to say that the code will log "R S" to the console but that's not correct. Anywhere outside a function, the keyword this is bound to the global object. If the keyword is used inside a function, then its value depends on how the function was invoked.
249
Can you nest a function declaration within a non function block?
You shouldn't but you can. Different browsers process them differently
250
Is the underscore _ allowed in variable naming?
Yes but it's not idiomatic
251
Give 3 invalid variable naming styles
- Start variable with a number, ex. let 34example - Hyphen anywhere, ex. let say-hi - Dot anywhere, ex. say.hi
252
What is an expression?
Any valid code that resolves to a value
253
Where can we not use statements?
As part of an expression let fava = (let lessa = 9) the let lessa is a statement
254
What does this log? function foo() { if (false) { var a = 1; } console.log(a); } foo();
undefined
255
What does this log function bar() { return 'world'; } var bar; console.log(bar()); bar = 'hello';
world
256
What does this log console.log(bar()); function bar() { return 'world'; } var bar = 'hello';
world
257
what do you think happens if you run this code? let foo = "hello"; function foo() { console.log("hello"); }
Syntax errors usually occur during the creation phase -- before "hoisting" has an effect on the code. Since processing occurs from the top down during the creation phase, the first identifier found is the foo variable on line 1. When the creation phase reaches the function declaration on lines 3-5, JavaScript already knows about the foo identifier, so it complains that foo has already been declared. The error occurs on line 3, not line 1.
258
Is there a function declaration in this code? let foo = function () { return function bar() {}; };
N0. A statement must begin with the function keyword to be a function declaration
259
How can you deep clone an array? let arr1 = [1, 2, 3, [1]];
let arr2 = JSON.parse(JSON.stringify(arr1)); arr1[3][0] = 'a'; console.log(arr1 === arr2); // false console.log(arr1[3] === arr2[3]); // false
260
What is JSON?
The JSON object contains methods for parsing JavaScript Object Notation
261
What do we call these associations between a name (or key) and a value?
Properties
262
The values represent the _____ of the object
attributes
263
What does this do? 0 in []; // false 0 in [1]; // true
The in operator checks whether an Object contains a specific key.
264
What does this log? let fava = []; fava[10] = 'lessa'; console.log(fava); console.log(3 in fava);
[empty × 10, 'lessa'] false
265
What does this return? {} == {}
false Like with arrays, two objects are considered equal by the == and === operators only if they are the same object:
266
How do you see the property internal flags of an object? let obj = { a:1, }
console.log(Object.getOwnPropertyDescriptors(obj)); {a: {…}} a: {value: 1, writable: true, enumerable: true, configurable: true} [[Prototype]]: Object
267
How can we change the internal properties of an object?
let prices = [400, 80, 375, 870]; Object.defineProperty(prices, 1, { enumerable: false }); for (var k in prices) { console.log(prices[k]); } // logs 400, 375, 870 ... the 80 is missing! However, even with enumerable flags set to false, other iteration methods such as the for…of loop or the built-in Array.prototype.forEach method will remain unchanged because they do not depend on this flag for instructions.
268
What does this log? var products = { "widget": 400, "gear": 80, "crank": 375, "lever": 870, }; Object.defineProperty(products, "gear", { enumerable: false }); var productKeys = Object.keys(products); console.log("productKeys: ", productKeys);
// logs productKeys: [ "widget", "crank", "lever" ]
269
What is considered a side effect?
Anything that causes JavaScript to look outside the program for a place to read or send data is a side effect. let date = new Date(); // side effect: accesses the system clock let rand = Math.random(); // side effect: accessed random number generator
270
How does a variable declared with ‘var' behave when it's declared inside a function?
It is not stored in the global object
271
How does 'continue' work in a loop?
It skips the current iteration and goes back to loop over the next item
272
How do you check if a value is NaN?
Number.isNaN(value)
273
Are there any comparison with NaN which results to true?
No. NaN === NaN => false
274
How do null and undefined behaved when compared with other objects?
If the two values are either null or undefined it returns true. If one is null or undefined and the other isn't it returns false.
275
How do non strict == equality operators behave in comparisons with different types if one is a number?
They convert the operands to numbers true == 1 => true
276
When one of the operands is an object, '+' will... ex. [1, 2] + 3
convert the whole thing to a string '1,23'