fundamentals Flashcards
((false && undefined) || (false || undefined));
undefined
What does the code return?
[…Array(3)]
[undefined, undefined, undefined]
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]
let bar = […foo, 4, 5, 6, …foo];
Which operator converts the non string to a string if the other operand is a string?
+
What does the code do?
Array.prototype.splice(0, 1) ;
It removes 1 element from energy, starting at index 0
What does this return?
‘4’ + 3
3 is coerced to the string ‘3’, so the result is ‘43’
What does this return?
‘fava’.charCodeAt(2)
The number of ‘v’ in the unicode: 118
undefined >= 1
// false – becomes NaN >= 1
What does this return?
1 + true
true is coerced to the number 1, so the result is 2
What happens here?
[1, 2] * 2;
[1, 2] becomes ‘1,2’, * 2 then NaN * 2 => NaN
NaN != NaN
true
When should you use try/catch/finally ?
A built in function or method can throw an error and you need to catch it
A simple guard clause is impractical
Operator after operand: (a++)
a = 1;
What is:
b = a++;
equivalent to “b = a; a++;”. so now b is 1 and a is 2
null == undefined
true
Braket notation is?
An operator. Not a method
‘11’ > 9
// true – ‘11’ is coerced to 11
Does javascript interpret a statement starting with a curly brace as an object literal?
No. it thinks it’s a block. Use parenthesis to force it to take it as an object literal
What does this return?
const str1 = ‘strunz’;
str1.endsWith(‘u’, 5);
false
How do you count all of the properties in an array, as opposed to only the indexed values?
Object.keys(array).length
Describe a mental model for how closures work
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
What does this return? Why?
‘50’ < ‘6’
true. ‘5’ < ‘6’
There is no coercion if same type
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 }
let obj = { …foo, …xyz };
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]
let bar = […foo];
How to you return 2 to the power of 3?
Math.pow(2, 3)
(‘a’ && (false || undefined) && ‘’);
undefined
How to check if a value is an integer?
Number.isInteger(value) => true or false
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:
undefined == null
true
How do you make a quantifier lazy?
Add a ‘?’ to the quantifier. Ex. *?
Operator before operand: (++a)
a = 1
c = ++a;
equivalent to “++a; c = a;”. so now c is 2 and a is 2
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
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
What does the regex specify?
p{3}
Exactly 3 occurrences of p
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;
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!’;
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
What does the code log?
let ocean = {};
let prefix = ‘Indian’;
ocean.prefix = ‘Pacific’;
console.log(ocean);
{ prefix: ‘Pacific’ }
What are the associations between a name (or key) and a value in an object?
properties
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’
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
What does this return?
0 == false //
true – becomes 0 == 0
What is an assignment?
a stand alone expression that assigns a new value to a variable
What does this return?
const str1 = ‘strunz’;
str1.startsWith(‘u’, 4);
false
11 > ‘9’
// true – ‘9’ is coerced to 9
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)
Atom shortcuts: Highlights all instances of the same word
command control g
What does the regex specify?
p{5,}
5 or more occurrences of p
how do you get the unique values from an array?
let array = [1, 1, 2, 3, 3]
[…new Set(array)]
=> [1, 2, 3]
What does this return?
1 + undefined
NaN
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
Which data type does Number.prototype.toFixed() return?
A string
Return a random integer between 0 and 3
Math.floor(Math.random() * 4);
What does the code return?
[…Array(3)].fill(2)
[2, 2, 2]
JavaScript style guides usually recommend using which notation when possible.
dot notation. as opposed to bracket
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;
What is this equal to?
[ …unused, …washed ]
unused.concat(washed);
((false || undefined) || (false && undefined));
false
Why is it a bad idea to run arithmetic operators on arrays?
Besides producing useless results they run without producing a warning!
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
Objects are containers for two things:
data (properties) and behaviour (methods)
undefined == ‘’
false
What does typeof null return and why?
Object. This is a historic bug. It’s too late to change it
How to get a value from an ascii code?
String.fromCharCode(68)
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
true > null
// true – becomes 1 > 0
What does this return?
‘a’.localeCompare(‘b’);
-1
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
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;
What does this return?
const str1 = ‘strunz’;
str1.startsWith(‘u’, 3);
true
What does this return?
‘’ == false
true – becomes ‘’ == 0, then 0 == 0
What is a type error?
When you call an inexistent method on an object or primitive.
What does the code return?
[…Array(3)].fill(2)
[2, 2, 2]
What is a reference error?
When you attempt to reference a variable or function that doesn’t exist
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’
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 };
123 <= ‘a’
// also false
What does this return?
true == ‘1’
true – 1 == 1
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.
123 > ‘a’
// false – ‘a’ is coerced to NaN; any comparison with NaN is false
let foo = false;
undefined — statements always return undefined
What is an expression?
any code that resolves to a value
What is an element of an array?
a value who has a non negative integer as it’s key (property name)
undefined === null
false
How to get a value from an ascii code?
String.fromCharCode(68)
What does the regex specify?
p{3, 7}
3 to 7 occurrences of p
How do non strict equality operators == coerce the following:
‘23’ == 23
It coerce the string to be a number
23 === 23 => true
What does the code do?
Array.from(‘foo’);
[“f”, “o”, “o”]
How do you add two decimal points to a value?
value.toFixed(2);
undefined == false
false
What does the code log?
let guess = false ? 1 : 2;
console.log(guess);
- Guess is false so it has the second argument passed to it
What is the regex for the anchor at the end of a string?
$
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;
What does the code log?
let guess = true ? 1 : 2;
console.log(guess);
- Guess is true so the first argument is passed to it
What does this return?
const str1 = ‘strunz’;
str1.endsWith(‘u’, 4);
true
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
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;
What does this return?
let friends = [‘Bob’, ‘Josie’, ‘Sam’];
let enemies = friends;
console.log(friends === enemies);
true
What does this return?
‘fava’.charAt(2);
‘v’
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
What does this return? why?
‘123’ * 3
369
all arithmetic operators other than + convert operands to numbers
What does this return?
‘0’ == false (two conversions)
true – becomes ‘0’ == 0, then 0 == 0
What does this return?
let friends = [‘Bob’, ‘Josie’, ‘Sam’];
let enemies = [‘Bob’, ‘Josie’, ‘Sam’];
console.log(friends[0] === enemies[0]);
true
What does this return?
null + true
1
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
Closures are:
A lexical, rather than a runtime feature
Which are the meta characters inside a character class?
^ \ - [ ]
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,
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]
What does this return?
‘hello’.charAt(1);
“e”
What is a closure?
a combination of a function and it’s lexical environment
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
What happens when the + operator has two operands and one is an object?
[1, 2] + 4
they are both converted to strings
‘1,24’
How do you remove the first property from foo?
let foo = {
a: ‘hello’,
b: ‘world’,
};
delete foo.a;
foo; // { b: “world” }
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.
Does the closure include all the existing variables within the scope of the function?
no. only the ones that the function needs
null <= false
// true – becomes 0 <= 0
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
What is the technical name for …theArgs?
function sum(…theArgs) {
//…
}
Rest parameter
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
How do you use BigInt?
append an n to the number
How to you convert a number, ex: 1234 into binary?
let num = 1234;
num.toString(2);
What happens here?
[1] * 2;
The operation becomes ‘1’ * 2, then the ‘1’ is converted to 1. So we get 1 * 2 => 2
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
What is an initializer?
the expression to the right of the = in a variable declaration
What happens when the + operator has two operands and neither are strings or object?
true + false
they are converted into numbers
1 + 0 => 1
What does this return?
5 + ‘41’
‘541’
true > false
// true – also becomes 1 > 0
How do you create an array from the ‘arguments’ pseudo array?
let args = Array.prototype.slice.call(arguments);
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];
What does this return?
true == ‘true’
false – 1 == NaN
Where should I not declare functions?
In non function blocks like “if else” statements. You should instead use arrow functions or function expressions
NaN == 0
false
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
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.
null == null
true
What does this return?
42 == true
false – becomes 42 == 1
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.
NaN === NaN
// false – even with the strict operator
NaN == NaN
false
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
What does this return?
const str1 = ‘strunz’;
str1.startsWith(‘u’);
false
What are higher order functions?
They are just normal functions with the extra ability to receive functions as arguments and also return them
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();
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
What does the regex cover: \w
\w matches all letters, number and underscore
null == false
false
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
What does the code return?
[…Array(3)].fill();
[undefined, undefined, undefined]
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
undefined == undefined
true
What is an array property name?
It’s a non negative index of an array. Values assigned to them are called elements
Which are the primitive types?
Strings, numbers, booleans, undefined and null
Can you use \b or \B word and non word boundaries in character classes?
No. \b means backspace in a character class
What is the difference between slice() and substring()
slice() is for arrays while substring() if for strings.
they return a new array or string
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
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.
How do you make “ “ three times bigger?
” “.repeat(3)
((false && undefined) || ‘a’ || ‘’);
‘a’
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
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
Make a RegExp to include word boundaries
let regex = RegExp(\\b${uniqueString}\\b
, ‘g’);
How do non strict equality operators == coerce the following:
0 == ‘\n’
It coerce the string to be a number
0 === 0 => true
How do you represent a non decimal character in regex?
\D
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’
What does the code return?
Array(3)
[empty × 3]
Return a random integer between 14 and 17
Math.floor(Math.random() * 4 + 14);
What is this equal to?
[ …unused, …washed ]
unused.concat(washed)
How else could you write array.join(‘’) ?
array.join``
What does the code log?
console.log(Array.from(‘foo’))
Array [“f”, “o”, “o”]
What does the code log?
console.log(Array.from([1, 2, 3], x => x + x))
Array [2, 4, 6]
What does the code log?
Array.from(new Set(‘abc’));
[“a”, “b”, “c”]
What does the code log?
[…‘abc’]
[“a”, “b”, “c”]
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
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
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
What is polymorphism?
Two objects of different types can respond differently to the same method call.
Remove a bunch of if else statements
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);
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.
What does the global window object do?
Provides variables and functions that are available throughout the program.
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’;
What is the ‘this’ keyword?
It’s a synonym for the execution context. It’s the object that is housing the property.
What does this return?
[1, 2, 3].splice(undefined, 1);
1
It removes the first element and mutates the array =>
[2, 3];
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];
Is -1 truthy?
It is. All negative numbers are truthy.
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”.
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.
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
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
What is logged by the code?
let a = 10;
let obj = {
a
}
obj.a += 10;
console.log(obj.a);
console.log(a);
20
10
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
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
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.
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?
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.
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.
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
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
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!
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
What is another name for the implicit function execution context
Implicit binding for functions
Does bind
execute a function?
No. It creates a new one permanently bound to the specified execution context
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.
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
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
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.
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
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()
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.
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.
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.
Define ‘this’
The current execution context of a function
How does strict mode affect ‘this’ in function calls?
Without strict mode ‘this’ refers to the window object. In strict mode it’s undefined
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.
The value of this changes based on …
…how you invoke a function, not how you define it.
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.
Does this method invocation use implicit or explicit execution context?
let obj = {
foo() {}
};
function bar() {}
obj.foo();
Implicit
What does this log?
function helloFactory() {
return function() {
console.log(‘hi’);
};
}
console.log(helloFactory());
The return function:
function() {
console.log(‘hi’);
};
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()();
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)
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.
When does the program garbage collect primitives and objects?
When the program has no more references to them
In what way are function declarations different from function expressions?
As an expression it means that there is a value returned — the function
Is garbage collection in JavaScript is responsible for memory deallocation?
Yes
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.
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’;
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.
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.”
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]
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]
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.
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.
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).
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);
Can a constructor be called without parenthesis if there are no arguments?
Yes, the parenthesis pair can be omitted: new FunctionName
What is another way to write
this = Object.create(Fava.prototype);
?
Object.setPrototype(this, Fava.prototype);
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
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
What should methods defined on the prototype always do?
Return the context object!!
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.
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
What does this do?
Object.create(obj)
It creates a new object and sets it’s dunder proto to point to obj
In node, where are variables declared with var or let stored?
var foo = ‘foo’
In the module scope
In node, where are variables declared without stored?
foo = ‘foo’
In the global object.
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
What do the following all point to?
function fava() {}
Array.prototype.__proto__
Function.prototype.__proto__
fava.prototype.__proto__
Object.prototype
What is ‘this’ in arrow functions?
‘this’ is the enclosing context where the arrow function is defined.
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
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.
Can you nest a function declaration within a non function block?
You shouldn’t but you can. Different browsers process them differently
Is the underscore _ allowed in variable naming?
Yes but it’s not idiomatic
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
What is an expression?
Any valid code that resolves to a value
Where can we not use statements?
As part of an expression
let fava = (let lessa = 9)
the let lessa is a statement
What does this log?
function foo() {
if (false) {
var a = 1;
}
console.log(a);
}
foo();
undefined
What does this log
function bar() {
return ‘world’;
}
var bar;
console.log(bar());
bar = ‘hello’;
world
What does this log
console.log(bar());
function bar() {
return ‘world’;
}
var bar = ‘hello’;
world
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.
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
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
What is JSON?
The JSON object contains methods for parsing JavaScript Object Notation
What do we call these associations between a name (or key) and a value?
Properties
The values represent the _____ of the object
attributes
What does this do?
0 in []; // false
0 in [1]; // true
The in operator checks whether an Object contains a specific key.
What does this log?
let fava = [];
fava[10] = ‘lessa’;
console.log(fava);
console.log(3 in fava);
[empty × 10, ‘lessa’]
false
What does this return?
{} == {}
false
Like with arrays, two objects are considered equal by the == and === operators only if they are the same object:
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
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.
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” ]
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
How does a variable declared with ‘var’ behave when it’s declared inside a function?
It is not stored in the global object
How does ‘continue’ work in a loop?
It skips the current iteration and goes back to loop over the next item
How do you check if a value is NaN?
Number.isNaN(value)
Are there any comparison with NaN which results to true?
No.
NaN === NaN
=> false
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.
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
When one of the operands is an object, ‘+’ will…
ex. [1, 2] + 3
convert the whole thing to a string
‘1,23’