JavaScript CheatSheet Flashcards

cheat sheet

1
Q

What are the (7) Array finding functions?

A

.indexOf()
.lastIndexof()
.length()
.at()
.find()
.findIndex()
.includes()

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

What are the (4) Creating array functions

A

.slice()
.of()
.flat()
.flatMap()

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

What are the (6) Adding array functions?

A

.splice()
.push()
.copyWithin()
.fill()
.concat()
.unshift()

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

Name (3) Removing array functions

A

.shift()
.pop()
.splice()

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

Name (2) Re-arranging array functions

A

.reverse()
.sort()

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

What are (4) functions that can be used for Misc. tasks?

A

.join()
.toString()
.isArray()
.indexOf()

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

What are (8) looping array functions

A

.filter()
.map()
.reduce()
.forEach()
.reduceRight()
.some()
.every()
.entries()

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

Adding Methods

A

.push()
.unshift()
.splice()

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

Reorganizing methods

A

.copyWithin()
.slice()
.splice()

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

Combining methods

A

.concat()

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

Removing methods

A

.pop()
.shift()
.splice()

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

Filter/Searching methods

A

.filter()
.find()
.findIndex()
.indexOf()
.lastIndexOf()

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

Sort alphabetically.

A
let a = ['d', 'j', 'a', 'b', 'c', 'g']
a.sort()
console.log(a) // ["a", "b", "c", "d", "g", "j"]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Sort in reversed alphabetical order.

A
let a = ['d', 'j', 'a', 'b', 'c', 'g']
a.sort().reverse()
console.log(a) // [ "j", "g", "d", "c", "b", "a"]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Sort numerically.

A
let a = [5, 10, 7, 1, 3, 2]
a.sort((a, b) => a - b)
console.log(a) // [ 1, 2, 3, 5, 7, 10]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Descending numerical sort (flip the a and b around).

A
let a = [5, 10, 7, 1, 3, 2]
a.sort((a, b) => b - a)
console.log(a) // [10, 7, 5 ,3, 2, 1]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Add anything to the end of an array.

A

.push()

let a = []
let b = {}
a.push(b)
console.log(a[0] === b) // true
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Add more than one item at a time to the end of an array

A

.push()

let x = ['a']
x.push('b', 'c')
console.log(x) // ['a', 'b', 'c']
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Add to the beginning of array and returns the new length of the array.

A

.unshift()

let x = ['c', 'd']
x.unshift('a', 'b') // 4
console.log(x) // ['a', 'b', 'c', 'd']
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Add element to an arbitrary location (second param 0).

A

.splice()

let a = [1, 2, 3, 4]
a.splice(2, 0, 'foo')
console.log(a) // [1, 2, "foo", 3, 4]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Copy part of an array to another location within the same array.

A

.copyWithin()

let a = ['a', 'b', 'c', 'd', 'e']
// target, start, end
array1.copyWithin(0, 3, 4)
console.log(a) // ["d", "b", "c", "d", "e"]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Returns a portion of an array selected with the start and end parameters.

A

.slice()

let a = ['ant', 'bison', 'camel', 'duck', 'elephant']
console.log(animals.slice(2)) // ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4)) // ["camel", "duck"]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Replace an arbitrary element in array (second param 1).

A

.splice()

let a = [1, 2, 3, 4]
a.splice(2, 1, 'foo')
console.log(a) // [1, 2, "foo", 4]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Create a new array from two arrays.

A

.concat()

let x = ['a', 'b', 'c']
let y = ['d', 'e', 'f']
let z = x.concat(y)
console.log(z) // ['a', 'b', 'c', 'd', 'e', 'f']
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Not a method, but create a new array from two arrays by spreading them.

A

...

let x = ['a', 'b']
let y = ['c', 'd']
let z = [...x, ...y]
console.log(z) // ['a', 'b', 'c', 'd']
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Removes the last element from array and returns it. Changes the length of the array.

A

.pop()

let a = ['a', 'b', 'c']
console.log(a.pop()) // c
console.log(a) // ["a", "b"]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Like pop but removes the first element from array and returns it. Also** changes the length** of the array.

A

.shift()

let a = ['a', 'b', 'c']
console.log(a.shift()) // a
console.log(a) // ["b", "c"]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Remove elements from the middle of an array. Param 1: index to start removing. Param 2: index to stop removing.

A

.splice()

let a = ['a', 'b', 'c', 'd', 'e']
a.splice(1, 3)
console.log(a) // ["a", "e"]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Keeps the items in the array that pass the test provided by the callback function.

A

.filter()

let a = ['foo', 'bar', 'fooz']
let b = a.filter(v => v.startsWith('foo'))
console.log(b) // ['foo', 'fooz']
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

Finds the first item in an array that matches.

A

.find()

let a = [5, 12, 8, 130, 44]
let b = a.find(v => v > 10)
console.log(b) // 12
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Like find but instead of returning the item, it returns the index.

A

.findIndex()

let a = [5, 12, 8, 130, 44]
let b = a.findIndex(v => v > 13)
console.log(b) // 3
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Finds the first index of an element. Returns ` -1` if not found.

A

.indexOf()

let a = ['foo', 'bar', 'baz']
console.log(a.indexOf('baz')) // 2
console.log(a.indexOf('quix')) // -1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

Like indexOf, but finds the last index of an element. Returns -1 if not found.

A

.lastIndexOf()

let a = ['foo', 'bar', 'baz', 'foo']
console.log(a.lastIndexOf('foo')) // 3
console.log(a.lastIndexOf('quix')) // -1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

Maps an array to another array by executing a callback function on each element.

A

.map()

let a = [1, 2, 3, 4]
let b = a.map(v => v * 2)
console.log(b) // 2, 4, 6, 8
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Same as map but it flattens the array, same as: [[]].map(v => v).flat().

A

.flatMap()

let a = [1, 2, 3, 4]
let b = a.flatMap(v => [v * 2])
console.log() // 2, 4, 6, 8
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

Executes a function for every element in array, does not return anything.

A

.forEach()

let a = [1, 2]
a.forEach(x => console.log(x))
// 1
// 2
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

Executes a user-supplied “reducer” callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element.

A

.reduce()

let a = [1, 2, 3, 4]
let b = a.reduce((acc, v) => acc + v)
// Basically: 1 + 2 + 3 + 4
console.log(b) // 10
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

Like reduce but reads the array from right to left.

A

.reduceRight()

let a = [1, 2, 3, 4]
let b = a.reduce((acc, v) => acc + v)
// Basically: 1 + 2 + 3 + 4
console.log(b) // 10
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

Tests if every item in the array passes the test.

A

.every()

let isBelow = v => v < 40
let a = [1, 30, 39, 29, 10, 13]
console.log(a.every(isBelow)) // true
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

Tests if some items in the array passes the test.

A

.some()
~~~
let isOver = v => v > 40
let a = [1, 30, 41, 29, 10, 13]
console.log(a.some(isOver)) // true
~~~

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

Test if an array contains a value.

A

.includes()

let a = [1, 2, 3]
let b = a.includes(2)
console.log(b) // true
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

Creates a new array from the given arguments.

A

Array.of()
~~~
Array.of(‘foo’, ‘bar’)
// [‘foo’, ‘bar’]
~~~

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

Creates a new array from an array-like or iterable object.

A

Array.from()

console.log(Array.from('foo')) // ['f', 'o', 'o']
console.log(Array.from([1, 2, 3], x => x + x)) // [2, 4, 6]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

Change all elements in an array to a static value.

A

.fill()

let a = [1, 2, 3, 4]
let b = a.fill(0, 2, 4)
console.log(b) // [1, 2, 0, 0]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

Returns an iterator object with key/value pairs for each index in the array.

A

.entries()

let a = ['a', 'b', 'c']
let iterator = a.entries()
console.log(iterator.next().value) // [0, "a"]
console.log([...iterator]) // [[0, "a"], [1, "b"], [2, "c"]]`]
46
Q

Returns an iterator object with values for each index in the array. Changes the data type from array to iterator.

A

.values()

let a = ['a', 'b', 'c']
let iterator = a.values()
for (const v of iterator) { console.log(v) } // a, b, c
47
Q

Returns an iterator object with keys for each index in the array. Changes the data type from array to iterator.

A

.keys()

let a = ['a', 'b', 'c']
let iterator = a.keys()
for (const v of iterator) { console.log(v) } // 1, 2, 3
48
Q

Turn array into a string by joining the element together.

A

.join()
~~~
let a = [‘foo’, ‘bar’, ‘baz’]
a.join() // foo,bar,baz
a.join(‘-‘) // foo-bar-baz
~~~

49
Q

Turn array or any other object into a string.

A

.toString()

let a = ['foo', 'bar', 'baz']
a.join() // foo,bar,baz
50
Q

Takes in integer value and returns the array element at that index. -1 returns the last element. ⚠️ Experimental technology.

A

.at() ⚠️

let x = ['a', 'b', 'c']
console.log(a.at(1)) // b
console.log(a.at(-1)) // c
51
Q

Gets the element count of an array.

A

.length
~~~
let x = [‘a’, ‘b’, ‘c’]
console.log(a.length) // 3
~~~

52
Q

Tests if a given variable is an array.

A

Array.isArray()
~~~
let a = [‘a’, ‘b’]
console.log(Array.isArray(a)) // true
~~~

53
Q

Flatten a nested array.

A

.flat()

let a = [0, 1, 2, [3, 4]]
let b = a.flat()
console.log(b) // [0, 1, 2, 3, 4]
54
Q

Reverses the order of an array.

A

.reverse()

let a = [1, 2, 3, 4]
a.reverse()
console.log(a) // [4, 3, 2, 1]
55
Q

Adding or removing an element at either end of an Array: (return value: item or new array length)

A

.push("⭐️")
.pop()
.unshift("⭐️")
.shift()
.unshift(arr.pop())

56
Q

Changing all of an Array (the input Array is modified and returned):

A

.fill("🟡")
.fill("🍕").map((val,idx) => idx)
.reverse()
.sort()
.copyWithin()

57
Q

Finding Array elements:

A

.includes()
.indexOf()
.lastIndexOf()
.find(x => x === 🍕)
.findIndex(x => x === 🍕)

58
Q

Creating a new Array from an existing Array:

A

.slice()
.splice()
.filter()
.map()
.flatMap()
.concat()

59
Q

Computing a summary of an Array:

A

.some()
.every()
.join()
.reduce()
.reduceRight()

60
Q

Listing elements and returning iterators

A

.keys() .values() .entries()`

61
Q

What is a JavaScript Iterator?

A

In JavaScript an iterator is an object which defines a sequence and potentially a return value upon its termination.

Specifically, an iterator is any object which implements the Iterator protocol by having a next() method that returns an object with** two properties**:

value
The next value in the iteration sequence.

done
This is true if the last value in the sequence has already been consumed. If value is present alongside done, it is the iterator’s return value.

Once created, an iterator object can be iterated explicitly by repeatedly calling next(). Iterating over an iterator is said to consume the iterator, because it is generally only possible to do once. After a terminating value has been yielded additional calls to next() should continue to return {done: true}.

Not all iterators are arrays
~~~
function makeRangeIterator(start = 0, end = Infinity, step = 1) {
let nextIndex = start;
let iterationCount = 0;

const rangeIterator = {
next() {
let result;
if (nextIndex < end) {
result = { value: nextIndex, done: false };
nextIndex += step;
iterationCount++;
return result;
}
return { value: iterationCount, done: true };
},
};
return rangeIterator;
}
~~~

62
Q

What is a Generator function in JavaScript?

A

While custom iterators are a useful tool, their creation requires careful programming due to the need to explicitly maintain their internal state. Generator functions provide a powerful alternative: they allow you to define an iterative algorithm by writing a single function whose execution is not continuous. Generator functions are written using the function* syntax.

When called, generator functions** do not initially execute their code**. Instead, they return a special type of iterator, called a Generator. When a value is consumed by calling the generator’s next method, the Generator function executes until it encounters the yield keyword.

The** function can be called as many times as desired**, and returns a new Generator each time. Each Generator may only be iterated once.

63
Q

What are JavaScript Iterables?

A

An object is iterable if it defines its iteration behavior, such as what values are looped over in a for...of construct. Some built-in types, such as Array or Map, have a default iteration behavior, while other types (such as Object) do not.

In order to be iterable, an object must implement the @@iterator method. This means that the object (or one of the objects up its prototype chain) **must have a property **with a Symbol.iterator key.

It may be possible to iterate over an iterable more than once, or only once. It is up to the programmer to know which is the case.

Iterables which can iterate only once (such as Generators) customarily return this from their @@iterator method, whereas** iterables which can be iterated many times **must return a new iterator on each invocation of @@iterator.

64
Q

Whats an example of a User defined Iterable

A

You can make your own iterables like this:
~~~
const myIterable = {
*Symbol.iterator {
yield 1;
yield 2;
yield 3;
},
};
~~~

User-defined iterables can be used in for...of loops or the spread syntax as usual.
~~~
for (const value of myIterable) {
console.log(value);
}
// 1
// 2
// 3

[…myIterable]; // [1, 2, 3]
~~~

65
Q

What are JavaScript’s built-in iterables?

A

String, Array, TypedArray, Map and Set are all built-in iterables, because their prototype objects all have a Symbol.iterator method.

66
Q

What are syntaxes that expect iterables?

A

Some statements and expressions expect iterables. For example: the for...of loops, spread syntax, yield*, and destructuring syntax.

67
Q

What are advanced generators?

A

Generators compute their yielded values on demand, which allows them to efficiently represent sequences that are expensive to compute (or even infinite sequences, as demonstrated above).

The next() method also accepts a value, which can be used to modify the internal state of the generator. **A value passed to next() will be received by yield **.

Note: A value passed to the** first** invocation of next() is always ignored.

Generators have a return() method that returns the given value and finishes the generator itself.

68
Q

What happens when you force a generator to throw an exception?

A

You can force a generator to throw an exception by calling its throw() method and passing the exception value it should throw. This exception will be thrown from the current suspended context of the generator, as if the yield that is currently suspended were instead a throw value statement.

If the exception is not caught from within the generator, it will propagate up through the call to throw(), and subsequent calls to next() will result in the done property being true.

69
Q

What is inheritance?

A

In programming, inheritance refers to passing down characteristics from a parent to a child so that a new piece of code can reuse and build upon the features of an existing one.

70
Q

How does JavaScript implement inheritance?

A

JavaScript implements inheritance by using objects. Each object has an internal link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype and acts as the final link in this prototype chain

It is possible to mutate any member of the prototype chain or even swap out the prototype at runtime, so concepts like static dispatching do not exist in JavaScript.

71
Q

How does JavaScript inherit properties with the prototype chain?

A

JavaScript objects are dynamic “bags” of properties (referred to as own properties). JavaScript objects have a link to a prototype object. When trying to access a property of an object, the property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached.

72
Q

How do you specify the [[Prototype]] of an object using the __proto__ syntax?

A

In an object literal like { a: 1, b: 2, __proto__: c }, the value c (which has to be either null or another object) will become the [[Prototype]] of the object represented by the literal, while the other keys like a and b will become the own properties of the object. This syntax reads very naturally, since [[Prototype]] is just an “internal property” of the object.

It’s worth noting that the { __proto__: … } syntax is different from the obj.__proto__ accessor: the former is standard and not deprecated.

Setting a property to an object creates an own property. The only exception to the getting and setting behavior rules is when it’s intercepted by a getter or setter.

Similarly, you can create longer prototype chains, and a property will be sought on all of them.

73
Q

Whats an example of setting a longer prototype chain?

A
74
Q

How does JavaScript inherit “methods”

A

JavaScript does not have “methods” in the form that class-based languages define them. In JavaScript, any function can be added to an object in the form of a property. An inherited function acts just as any other property, including property shadowing as shown above (in this case, a form of method overriding).

When an inherited function is executed, the value of this points to the inheriting object, not to the prototype object where the function is an own property.

75
Q

What are Constructors? why do you use them?

A

Constructors are functions called with new.

We say that new Box(1) is an instance created from the Box constructor function. Box.prototype is not much different from the boxPrototype object we created previously — it’s just a plain object. Every instance created from a constructor function will automatically have the constructor’s prototype property as its [[Prototype]] — that is, Object.getPrototypeOf(new Box()) === Box.prototype.

Constructor.prototype by default has one own property: constructor, which references the constructor function itself — that is, Box.prototype.constructor === Box. This allows one to access the original constructor from any instance.

Note: If a non-primitive is returned from the constructor function, that value will become the result of the new expression. In this case the [[Prototype]] may not be correctly bound — but this should not happen much in practice.

76
Q

How are Constructors related to Classes?

A
  • you can rewrite constructors as classes

Classes are syntax sugar over constructor functions, which means you can still manipulate Box.prototype to change the behavior of all instances. However, because classes are designed to be an abstraction over the underlying prototype mechanism, we will use the more-lightweight constructor function syntax for this tutorial to fully demonstrate how prototypes work.

Because Box.prototype references the same object as the [[Prototype]] of all instances, we can change the behavior of all instances by mutating Box.prototype.

77
Q

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

A
78
Q

== vs === in JavaScript

A

Let’s compare some variables. There are two ways you can do that.

== only checks for the value

=== checks for value + type

let a = 5 // number
let b = ‘5’ // string

console.log(a == b) // true

console.log(a === b) // false

79
Q

The map array method

A

map creates a new copy of the original array. We use it when we want to do something with the elements of the original array but don’t want to change it.

map iterates over the original array and takes a callback function (which we’ll cover later) as an argument. In the callback function, we tell it what to do with the elements.

const a = [1,2,3,4,5]

// Create a new array which multiplies every element by 2

const d = a.map(function(item){ return item*2 })

console.log(d) // [2,4,6,8,10]

80
Q

What are the differences between .forEach() and .map()?

A
  • First of all, map returns a new Array, but forEach doesn’t.

And second, you can do method chaining in map but not in forEach.

Note: map and forEach don’t mutate (change) the original array.

81
Q

What are the two ways to make a function in JavaScript?

A

function a(){
console.log(‘I am a normal function’);
}

const b = () => {
console.log(‘I am an arrow function’)
}

// They are essentially the same but with a few differences which we will cover as we go along this tutorial.

// We can pass variables as arguments
const c = (name) => {
console.log(My name is ${name})
}

// `` template literal are a new addition to the language. Very useful for string formatting. Values are accessed using ${} inside them.

// We can even pass functions as arguments to a function. Will see more on this when we try to understand closures.

const greet = () => {
const prefix = ‘Mr’
return (name) => {
console.log(${prefix} ${name}, welcome!)
}
}

console.log(greet()(‘Jack’))

82
Q

What are the 3 types of scope?

A

Global (declaration outside of any function)
Function (declaration inside a function)
Block (declaration inside a block)

Remember from before that var is globally scoped whereas let and const are block scoped. Let’s understand that now.

83
Q

What is the MDN definition of a closure?

A

A function bundled together with its lexical environment forms a closure.

84
Q

What is a lexical environment?

A

It is essentially the surrounding state – the local memory along with the lexical environment of its parent.

function x() {
var a = 7
function y() {
console.log(a)
}
return y
}

var z = x()
console.log(z) // [Function: y]
z()

When x is invoked, y is returned. Now, y is waiting to be executed. Kind of like a loaded gun waiting to be shot! 🔫

So, when we finally invoke z, y is invoked. Now, y has to log a so it first tries to find 🔍 it in the local memory but it’s not there. It goes to its parent function. It finds a there.

Voila! There you have it - this is closure.

Even when functions are returned (in the above case y) they still remember their lexical scope (where it came from)

Totally unrelated quote for kicks 👻:

They may forget what you said - but they will never forget how you made them feel - Carl W. Buehner

85
Q

What are the advantages of closures in JavaScript?

A
  • Currying

let add = function (x) {
return function (y) {
console.log(x + y)
}
}

let addByTwo = add(2)
addByTwo(3)

  • Data Hiding/Encapsulation

Suppose you want to create a counter application. Every time you call it, the count increases by 1. But you don’t want to expose the variable outside the function. How to do it?

86
Q

What are the disadvantages of closures?

A

Overconsumption of memory or memory leaks can happen.

For example, the closed-over-variable will not be garbage collected. This is because, even if the outer function has run, the returned inner function still has a reference to the closed-over-variable.

Note: Garbage collection basically removes unused variables from the memory automatically.

87
Q

What is Hoisting in JavaScript?

A

This is JavaScript’s default behavior of moving declarations to the top of the program.

var declaration is hoisted up and initialized with undefined.
let and const declarations are hoisted up but not initialized.
function definitions are also hoisted up and stored as they are.

88
Q

localStorage

A

localStorage: Data persists even after closing your session

89
Q

sessionStorage

A

You lose your data when your session is over, like when you close the browser on the tab.

90
Q

what’s the difference between debounce and throttling

A

Let’s take the search bar 🔍 example from above. When we are debouncing the input field, we are saying to only fetch the data when the difference between two keyup events is at least 300 ms.

In the case of throttling, we make a function call only after a certain period of time.

Suppose that you are searching for an encyclopedia in the search bar. The first call is made on e and it took us 300 ms to reach p. The next call will be made then only. All the events in between will be ignored.

So, to summarize, debouncing is when the difference between two keyup events is 300 ms. And throttling is when the difference between two function calls is 300 ms. Basically, the function is called after a certain interval of time.

91
Q

Async and defer in JavaScript

A

Async and defer are boolean attributes which can be loaded along with the script tags. They are useful for loading external scripts into your web page.

92
Q

Async + defer…

When Script tag inside <head>

A
93
Q

Async + defer…

Script tag inside <body>

A
94
Q

Async + defer…

async when inside the <head> tag

A

If you want to load external script which is not dependant on the execution of any other scripts, use async.

Note: The async attribute does not guarantee the order of execution of scripts.

95
Q

Async + defer…

defer when inside the <head> tag

A

If there are multiple scripts which are dependant on each other, use defer. Defer script are executed in the order which they are defined.

96
Q

Timers in JavaScript – setTimeout, setInterval, clearInterval ⏱️

A

The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.

setInterval() does the same for specified intervals.

You use clearInterval() to stop the timer.

97
Q

what happens when you start a new program and just log “this”?

A

console.log(this)

It will point to the window object.

However, if you then define an object, it will bind to the object…
~~~
function myFunc() {
console.log(this)
}

const obj = {
bool: true,
myFunc: myFunc,
}

obj.myFunc()
~~~
this now is binded to the object.

But if you do
myFunc() // window

We again get the window object. So, we can see that the value of this depends on how and where are we doing the calling.

98
Q

Whats an example of Implicit Binding.

A

The value of this depends on how and where are we doing the calling.

99
Q

What is Explicit binding?

A

Explicit binding is when you force a function to use a certain object as its this.

We are using this properly, but can you see the problem with the above code?

We are repeating code. And one of the principles of good programming is keep your code DRY! (Don’t Repeat Yourself)

So, let’s get rid of displayName_2 and simply do:

student_1.displayName_1.call(student_2) // Raj

call forced displayName_1 to use the second object as its this.

100
Q

What are the three methods used to explicity bind this?

A
  • call()
  • apply()
  • bind()
101
Q

What are Higher Order Functions?

A

Functions that either TAKE IN functions as parameters or RETURN other functions.
ex. build in array functions .map() and .filter() examples of higher order functions

102
Q

What are arrow functions and name a key difference between arrow functions and regular javascript functions.

A
  • arrow is ES6
  • arrow one liners don’t need return in curly braces
  • arrows don’t need the function keyword
    KEY difference: you cannot use arrow functions as object constructors.
103
Q

When does the JS event loop check the event queue?

A

JS event loop only checks the event queue if the call stack is empty. The call stack takes precedence. Only when all the functions have finished running does it check the event loop.

104
Q

How to use the slice() JavaScript array method

A
  • can be used to create a copy of an array or return a portion of an array.
  • does not alter the original array but instead creates a shallow copy

MDN: “The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array…”

  • Two arguments are INDEXES
  • the end is NOT included.
  • 1st arg = inclusive, 2nd arg = exclusive.

BASIC SYNTAX:
slice(optional start parameter, optional end parameter)

105
Q

Heuristics for slice() JavaScript method :

arr.slice(i)

A

For any array, where i and/or j is an index, and n is a number of elements, you can remember a few common operations as follows:

  1. From i to the end — elements in a range starting with the ith element, ending with the last element in the array: arr.slice(i) - starting index and everything after
106
Q

Heuristics for slice() JavaScript method :

arr.slice(0, i + 1)

A
  1. From the beginning to i — elements in range starting with the beginning of the array and ending with the ith element: arr.slice(0, i + 1)

Remember the “cut to the left” exclusion rule means that to get the ith element, we need to add one (1) to our second argument.

107
Q

Heuristics for slice() JavaScript method :

arr.slice(i, j + 1)

A
  1. From i to j — elements in a range starting with the ith element and ending with the jth element: arr.slice(i, j + 1)

Remember the “cut to the left” exclusion rule means that to get the jth element, we need to add one (1) to our second argument.

108
Q

Heuristics for slice() JavaScript method :

arr.slice(0, n)

A
  1. The first n items of the array: arr.slice(0, n)

This is of course the same case as #2, phrased differently. If we are concerned with the number of elements rather than the index, our inputs are more intuitive.

109
Q

Heuristics for slice() JavaScript method :

arr.slice(-n)

A
  1. The last n items of the array: arr.slice(-n)

Because negative indexes “wrap around” in JavaScript, we can quickly determine the last n elements; arr.slice(-5) therefore starts 5 from the end, and since our first argument is inclusive, we will get all five elements.

110
Q

Heuristics for slice() JavaScript method :

arr.slice(i, i + n)

A
  1. These n elements starting with the ith element: arr.slice(i, i + n)

This logic follows from #4. After all, if i = 0, our second argument will be 0 + n, a.k.a. n. Because of zero indexing, if we consider the number of elements rather than the index, our “cut to the left” exclusion rule works in our favor, allowing us to simplify to n elements.

111
Q

splice() traits

A

splice() is destructive. This means it alters the original array, in this case by removing the elements in the specified range.

  • splice()’s second argument is not an index, but a number of elements to be removed. This means while the above example (slice(1, 6)) would return [1, 2, 3, 4, 5] , splice(1, 6) will return [ 1, 2, 3, 4, 5, 6].
  1. splice() can also take a third argument that tells the method to insert a given element after the index specified in the first argument.