JavaScript Flashcards

1
Q

What is the purpose of variables?

A

Variables let scripts be reusable, changing the values used each time the script is run
Variables let the computer remember a value for future use
According to MDN, variables allow an unpredictable value to be accessed by a predetermined name. (And that variables are named references to values)

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

How do youdeclarea variable?

A

Use a keyword like var (or let or const but don’t use them here at LFZ) and then the name of the variable myVar
Name variables with camelCase
Variable type does not need to be specified in JavaScript

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

How do you initialize (assign a value to) a variable?

A

Use variable name and the assignment operator followed by the value to assign/initialize with (ending with a semicolon) myVar = 23;

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

What characters are allowed in variable names?

A

letters, dollar sign ($), underscores (_), and numbers (but cannot start with a number)

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

What does it mean to say that variable names are “case sensitive”?

A

Two variable names that are the same letters but with different capitalization will be considered two different variables

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

What is the purpose of a string?

A

Stores text values or a string of characters that wouldn’t make sense to JavaScript

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

What is the purpose of a number?

A

Stores numeric values not only for calculations but also numeric properties such as screen size. Stores positive and negative integers and decimals

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

What is the purpose of a boolean?

A

Like a light switch, it indicates one of two states (true or false)
Allows for logic and decisions

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

What does the=operator mean in JavaScript?

A

= is the assignment operator, meaning it assigns values to variables (or properties, or other stuff)

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

How do you update the value of a variable?

A

Assign it a value again, no keyword at the start

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

What is the difference betweennullandundefined?

A

null is usually the intentional absence of a value whereas undefined is assigned to newly created variables with no assignment yet (a sort of default absence of value)
null is an object while undefined has type of undefined
JavaScript can create undefined (and leave it to JS to do) but only you can create null

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

Why is it a good habit to include “labels” when you log values to the browser console?

A

Without labels, the output can quickly become a very confusing screen of seemingly random values

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

Give five examples of JavaScript primitives.

A

string, number, boolean, undefined, null, bigint, symbol

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

What are the boolean and numeric values of null and undefined?

A

Both are considered false

null will be 0 in numeric contexts and undefined will be NaN

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

What are objects used for?

A

Objects group together related variables and functions into a single object

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

What are object properties?

A

Properties are like variables that are part of an object, they store values like numbers, strings, booleans, arrays, and objects

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

Describe object literal notation.

A

Object literal notation is a way to create an object
Begins with curly braces, then has property/method name followed by a :, then the value/function for that property/method, and commas to separate these key-value pairs (all within the curly braces). Usually this is assigned to a variable as usual

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

How do you remove a property from an object?

A

delete myObj.propertyToRemove or delete myObj['propertyToRemove']

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

What are the two ways to get or update the value of a property?

A

Dot notation (myObj.propertyName) or bracket notation (myObj['propertyName'])

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

What are arrays used for?

A

Stores list-like information, a collection of values that are all related to each other in some way

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

Describe array literal notation.

A

Square brackets with values inside delineated by commas

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

How are arrays different from “plain” objects?

A
  • The keys are incrementing numbers (indexes)
  • Objects can do dot notation
  • Objects don’t have order
  • Empty arrays have a method built in already, length
  • Adding to objects is different from adding to arrays
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What number represents the first index of an array?

A
  • In JavaScript, indexes start at 0
  • Originally in lower level languages, index meant how many memory spaces to move from the beginning to get the value you want (move 0 spaces to get the first item)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is thelengthproperty of an array?

A
  • It contains the number of items in the array, built into arrays
  • Number of indexes in there
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

How do you calculate the last index of an array?

A

myArray.length - 1

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

What is a function in JavaScript?

A

Packaging code up into a reusable and easily referenced form

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

Describe the parts of a functiondefinition.

A

function optionalName(param1, param2, ...) { code definition; optional return value }

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

Describe the parts of a functioncall.

A

optionalName(arg1, arg2, ...)

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

When comparing them side-by-side, what are the differences between a functioncalland a functiondefinition?

A

Calls do not have the keyword function in front, nor do they have the {} to indicate what will happen within the function. Calls also take arguments, while functions have parameters.

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

What is the difference between aparameterand anargument?

A

Parameters are part of the function definition. Arguments are passed into a function call.

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

Why are functionparametersuseful?

A

They make the code within the function reusable for multiple variables so the work can be repeatedly done on similar things

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

What two effects does areturnstatement have on the behavior of a function?

A

Stops the execution of the function, meaning no code beyond the first return is run.
Return replaces a function call with the return value

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

Why do we log things to the console?

A

So that we can see what our code is doing throughout the script and check that it is working as intended

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

What is a method?

A

A function which is a property of an object

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

How is a method different from any other function?

A

They are specific to the object that they belong to and must be called with reference to its object

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

How do you remove the last element from an array?

A

myArray.pop() removes and returns the last element from an array

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

How do you round a number down to the nearest integer?

A

Math.floor(myNumber)

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

How do you generate a random number?

A

Math.random() generates a pseudo-random number between 0 and 1 (inclusive of 0, not inclusive of 1). Multiply this by the range needed to get a random number between x and y.

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

How do you delete an element from an array?

A

myArray.splice(startIndex, numOfItemsToRemove) to remove from specific locations
myArray.pop() deletes from the end
myArray.shift() deletes from the beginning

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

How do you append an element to an array?

A

myArray.push() adds to the end (to append)
myArray.splice(startIndex, 0, elementToAdd, nextElementToAdd, ...) for adding elements at a specific location in the array
myArray.unshift() adds to the beginning

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

How do you break a string up into an array?

A

myString.split('separator') breaks up a string along the separator supplied

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

Do string methods change the original string? How would you check if you weren’t sure?

A

No, I would try using a few string methods on a string and then log the value of the string to see if it had undergone any transformations

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

Give 6 examples of comparison operators.

A

===, !==, >, >=, `

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

What data type do comparison expressions evaluate to?

A

boolean

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

What is the purpose of anifstatement?

A

Allows our programs to make decisions, executing some code sometimes and other code (or no code) at other times based on some condition

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

Iselserequired in order to use anifstatement?

A

No, it will simply not execute the code in the code block of the if statement and then continue on with the rest of the code

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

Describe the syntax (structure) of anifstatement.

A

if (expression that evaluates to boolean) {code} else {code}

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

What are the three logical operators?

A

&&, ||, !

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

How do you compare two different expressions in the same condition?

A

Wrap each expression in parentheses, then use a comparison operator between them to have the entire expression evaluate down to a single boolean
Also, use logical operators

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

What is the purpose of a loop?

A

Do a block of code a repeated number of times

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

What is the purpose of aconditionexpression in a loop?

A

To check if another loop should be executed (and to have a way to stop looping at some point)

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

What does “iteration” mean in the context of loops?

A

One execution of the code block

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

_When_does theconditionexpression of awhileloop get evaluated?

A

At the beginning of each iteration, including the first

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

_When_does theinitializationexpression of aforloop get evaluated?

A

At the beginning of the loop (just once)

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

_When_does theconditionexpression of aforloop get evaluated?

A

At the beginning of each iteration, including the first

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

_When_does thefinalexpression of aforloop get evaluated?

A

At the end of each iteration

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

Besides areturnstatement, which exits its entire function block, which keyword exits a loop before itsconditionexpression evaluates tofalse?

A

break

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

What does the++increment operator do?

A

Increments the operand that comes before the ++ by 1 and returns the current value
- Both incrementation and substitution

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

How do you iterate through the keys of an object?

A

Use a for ... in loop

- for (var key in object) {code here}

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

What is a “model”?

A

A model is a representation, usually imperfect, of some other thing. Usually used to better understand that other thing, or make some sort of work with that thing easier.

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

Which “document” is being referred to in the phrase Document Object Model?

A

The web page as a whole

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

What is the word “object” referring to in the phrase Document Object Model?

A

The objects of the document, in this case the nodes

JavaScript object data type, storing key-value pairs

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

What is a DOM Tree?

A

A DOM Tree is a representation of the HTML document or a chunk of HTML created by the browser with four node types (document, element, attribute, text)

64
Q

Give two examples ofdocumentmethods that retrieve a single element from the DOM.

A

.querySelector() and .getElementById()

Use only .querySelector() because it’s newer, and reduces number of tools to use

65
Q

Give one example of adocumentmethod that retrieves multiple elements from the DOM at once.

A

.querySelectorAll(), which is slower than .getElementsByClassName() and .getElementsByTagName()
Use only .querySelectorAll()

66
Q

Why might you want to assign the return value of a DOM query to a variable?

A

So that we can work with the return value multiple times without having to requery the tree each time

67
Q

Whatconsolemethod allows you to inspect the properties of a DOM element object?

A

console.dir()

68
Q

Why would ascripttag need to be placed at the bottom of the HTML content instead of at the top?

A

The HTML elements must be loaded before JavaScript can access them, so it must be placed after all of the elements

69
Q

What doesdocument.querySelector()take as its argument and what does it return?

A

It takes a CSS selector as a string and returns the first element node that matches the CSS selector

70
Q

What doesdocument.querySelectorAll()take as its argument and what does it return?

A

It also takes a CSS selector as a string and returns a NodeList, an array-like object of the matching elements in the document

71
Q

What is the purpose of events and event handling?

A

Events and event handling allow us to run code when users interact with the web page, increasing functionality and making the page feel more responsive

72
Q

Are all possible parameters required to use a JavaScript method or function?

A

No, some are optional

73
Q

What method of element objects lets you set up a function to be called when a specific type of event occurs?

A

.addEventListener()

74
Q

What is a callback function?

A

A function called as an argument by another function

75
Q

What object is passed into an event listener callback when the event fires?

A

An event object, based on what was set in the event listener (an object with all the data about the event that just occurred)

76
Q

What is theevent.target? If you weren’t sure, how would you check? Where could you get more information about it?

A

The DOM element that was the start point for the event. (commonly the element you put the event listener on, but it could be an element within the element you put the event listener on)
- Put one event listener on a div holding 50 button and event.target will indicate which button was clicked
- This is checked from logging event.target to the console.
- I would check MDN’s documentation on events, or even specifically the target property of event objects.
- From MDN:
>The read-onlytargetproperty of theEventinterface is a reference to the object onto which the event was dispatched.

77
Q

What is the difference between these two snippets of code?

```js
element.addEventListener('click', handleClick)
```

```js
element.addEventListener('click', handleClick())
```
A

The first will call handleClick(event) when the targeted element is clicked.
The second will call the return value of calling the function handleClick() which could be another function

78
Q

What is theclassNameproperty of element objects?

A

The className property holds the class attribute and allows us to set the class attribute of the element specified by the element object

79
Q

How do you update the CSS class attribute of an element using JavaScript?

A

Specify the element to change using querySelector() or something similar, and set the className property on the returned element object of that method

80
Q

What is thetextContentproperty of element objects?

A

The textContent is a property of a node, and it holds the concatenation of the text content of the targeted element and its descendants

81
Q

How do you update the text within an element using JavaScript?

A

Specify the element with querySelector or similar, and then set the textContent property on the returned element

82
Q

Is theeventparameter of an event listener callback always useful?

A

No, but it should still always be on the function even if it isn’t used
We only need it if we’re not sure what element was interacted with and what element to change

83
Q

Would this assignment be simpler or more complicated if we didn’t use a variable to keep track of the number of clicks?

A

It would be a little simpler to not have an additional variable to account for, but then you have to extract the number from the text content of the HTML

84
Q

Why is storing information about a program in variables better than only storing it in the DOM?

A

It’s much easier to modify and use the variable in JavaScript rather than querying for it in the DOM

85
Q

What event is fired when a user places their cursor in a form control?

A

'focus' event

86
Q

What event is fired when a user’s cursor leaves a form control?

A

'blur' event

87
Q

What event is fired as a user changes the value of a form control?

A

'input' event

88
Q

What event is fired when a user clicks the"submit"button within a``?

A

'submit' event

89
Q

What does theevent.preventDefault()method do?

A
It essentially prevents an event from triggering its default behavior, and putting it at any stage of event flow cancels the event
Preventing text (or certain kinds of text) from being input into a text `input` or preventing a checkbox from being checked upon being clicked
90
Q

What does submitting a form withoutevent.preventDefault()do?

A

The form that the submit is in would get submitted to a server, the regular behavior

91
Q

What property of a form element object contains all of the form’s controls?

A

.elements

92
Q

What property of a form control object gets and sets its value?

A

.value

93
Q

What is one risk of writing a lot of code without checking to see if it works so far?

A

You can end up going down the wrong path, writing code based on false assumptions that would then need to be entirely undone

94
Q

What is an advantage of having your console open when writing a JavaScript program?

A

You can incorporate logging into your code and see it as your test your page, as well as try bits of code (running functions, looking at variable contents, etc.) as you go along

95
Q

Does thedocument.createElement()method insert a new element into the page?

A

No, it simply returns a new element node to the JavaScript environment

96
Q

How do you add an element as a child to another element?

A

$parentElement.appendChild($childElement);
.append(param1, param2, ...) can append multiple at once
.insertBefore() as well

97
Q

What do you pass as the arguments to theelement.setAttribute()method?

A

.setAttribute(name-of-attribute, value-of-attribute)

98
Q

What steps do you need to take in order to insert a new element into the page?

A

Query for/create the parent element
Create the element using document.createElement()
Modify this newly created element (element.textContent, element.setAttribute(), creating and appending a text node, etc.)
Query the document for the (soon-to-be) parent element of this new element
$parentElement.appendChild($newElement) or potentially use .insertBefore() to put it at a specific location among siblings

99
Q

What is thetextContentproperty of an element object for?

A

Gets and sets the text content of an element and its children (through the DOM interface objects)

100
Q

Name two ways to set theclassattribute of a DOM element.

A

$element.setAttribute('class', 'new-class')
$element.className = 'new-class'
Also $element.classList = ['new-class'] for a more roundabout way dealing with arrays

101
Q

What are two advantages of defining a function to do create something (like the work of creating a DOM tree)?

A

We can create consistently structured things with different data repeatedly and concisely
We can tie the function that creates things to event listeners

102
Q

What is theevent.target?

A

It is “a reference to the object onto which the event was dispatched”
From the exercises, it seems to be what element was interacted with to trigger the event to fire

103
Q

Why is it possible to listen for events on one element that actually happen on its descendent elements?

A

Bubbling
Clicking on a descendent element is technically clicking on parent elements (clicking a button on an a in a li in a ul is clicking on all three, but the interpretation starts at the most specific )

104
Q

What DOM element property tells you what type of element it is?

A

element.tagName

105
Q

What does theelement.closest()method take as its argument and what does it return?

A

It takes a string containing a CSS selector
It returns the first element that matches the CSS selector, starting from the element it is called upon itself and moving up its ancestors toward the root (null if it finds nothing)
Like reverse .querySelector()

106
Q

How can you remove an element from the DOM?

A

element.remove() will remove that element from the DOM, nothing else required

107
Q

If you wanted to insert new clickable DOM elements into the page using JavaScript, how could you avoid adding an event listener to every new element individually?

A

Add the event listener to the parent element upon which you are calling .appendChild($newClickableElement) and have the function only activate on the type of element you want it to act upon

108
Q

What is theevent.target?

A

The element that was used in triggering the event

109
Q

What is the affect of setting an element todisplay: none?

A

The element and its child elements are no longer displayed, and it has no effect on the layout (document is rendered as if it didn’t exist)
Alternative: visibility property which allows it to take up the space it normally would but not appear (think typing-tutor assignment with the congratulatory text)

110
Q

What does theelement.matches()method take as an argument and what does it return?

A

It takes for an argument a CSS selector as a string

It returns a boolean value based on if it would have been found using that CSS selector

111
Q

How can you retrieve the value of an element’s attribute?

A

element.getAttribute('my-attribute')

112
Q

At what steps of the solution would it be helpful to log things to the console?

A

At all steps, but especially the ones where you are having trouble understanding what is happening or what the objects you are working with are

113
Q

If you were to add another tab and view to your HTML, but you didn’t use event delegation, how would your JavaScript code be written instead?

A

Each tab would need an event listener, and any additional tabs would need additional event listeners

114
Q

If you didn’t use a loop to conditionally show or hide the views in the page, how would your JavaScript code be written instead?

A

Each of the views would have to be queried individually, and when a click event happens there would have to be an if statement for each one
If the view is the one to be made visible, make it visible. Otherwise make it invisible. Repeat for the other two views.

115
Q

What is JSON?

A

JavaScript Object Notation, a way to store data in a string in a certain format
A standard text-based format for representing structured data based on JavaScript object notation

116
Q

What are serialization and deserialization?

A

To serialize an object is to put it in a series format, encoding it to be read in serial (a stream of bytes)
Deserialization is taking that stream of bytes and reconstructing (parsing) it back into an object

117
Q

Why are serialization and deserialization useful?

A

It allows complex data types to be transmitted one byte at a time, as is done over a network
Serialization allows data to be easily transmissible somewhere else, and deserialization allows us to more easily work with it

118
Q

How do you serialize a data structure into a JSON string using JavaScript?

A

JSON.stringify(myDataStruct)

119
Q

How do you deserialize a JSON string into a data structure using JavaScript?

A

JSON.parse(myDataAsString)

120
Q

How do you store data inlocalStorage?

A

localStorage.setItem('key', 'stringValue')

121
Q

How do you retrieve data fromlocalStorage?

A

localStorage.getItem('key')

122
Q

What data type canlocalStoragesave in the browser?

A

Only string types (UTF-16 string format, 2 bytes per character)

123
Q

When does the'beforeunload'event fire on thewindowobject?

A

Just before the window, the document, and its resources are about to be unloaded (discarded)

124
Q

What is the scope of localStorage?

A

Domain level storage

125
Q

What is amethod?

A

A function which is a property of an object

126
Q

How can you tell the difference between a method_definition_and a method_call_?

A

Method definitions are like function definitions, but they happen in the definition of an object property (or being assigned to an object property).
Calling a method is simply the object with a function call attached (object.methodCall())

127
Q

Describe methoddefinitionsyntax (structure).

A

As a property in an object definition: var myObj = {methodName: function (x, y) {...} }

128
Q

Describe methodcallsyntax (structure).

A

myObj.methodName(4, 5);

129
Q

How is a method different from any other function?

A

It must be called with an object

130
Q

What is thedefining characteristicof Object-Oriented Programming?

A

OOP uses objects to store the state of the program and to hold the functions that will be used. Objects are the primary interface.
Objects have data (properties) and behavior (methods) that act upon the data are stored in the same place

131
Q

What are the four “principles” of Object-Oriented Programming?

A
Abstraction - complex behavior is implemented behind the scenes so that subsequent work can be done without worrying about how the underlying mechanisms are handled
Encapsulation - restrict access to object properties, and keep data and methods that act on that data together
Inheritance - things can be constructed from another thing so that it has similar properties and methods and can be used in a similar way (a class can be used to create many similar objects)
Polymorphism - something can be called the same but work differently (`string.len()` and `array.len()` both use `.len()` but they operate differently)
132
Q

What is “abstraction”?

A

A simplified interface to something complex (think light switch vs how all the wires and current and power sources work to send electricity to light bulb)

133
Q

What does API stand for?

A

Application Programming Interface

134
Q

What is the purpose of an API?

A

Allow for a standard way to interface with some technology with predictable, simplified behavior
UI connects person to computer, API connects software to software
APIs hide software details so that a programmer can only focus on relevant pieces. This also alleviates the need to worry about how the software changes, with the expectation that the API will remain consistent.
APIs are like the light switch for the electrical system in your house

135
Q

What isthisin JavaScript?

A

An implicit parameter, determined at call time, and refers to the object to which it is attached (left of the .)
Alternatively, the object you’re currently working within

136
Q

What does it mean to say thatthisis an “implicit parameter”?

A

It is always an available parameter to a function, and should not be explicitly stated in the function definition
Bonus: another implicit parameter is arguments which returns all of the arguments as an array

137
Q

_When_is the value ofthisdetermined in a function;call timeordefinition time?

A

Call time, this can refer to new objects depending on when it is called

138
Q
What does`this`refer to in the following code snippet?   
    ```js
    var character = {
      firstName: 'Mario',
      greet: function () {
        var message = 'It\'s-a-me, ' + this.firstName + '!';
        console.log(message);
      }
    };
    ```
A

We don’t know! We are not calling the method, this is not yet a thing!
Just like a parameter doesn’t exist and has no value until the function is called, this (an implicit parameter) also doesn’t exist and has no value

139
Q

Given the abovecharacterobject, what is the result of the following code snippet? Why?

js
    character.greet();
   
A

'It's-a-me, Mario! because this.firstName will be replaced at call time with character.firstName which is Mario

140
Q
Given the above`character`object, what is the result of the following code snippet? Why?
    ```js
    var hello = character.greet;
    hello();
    ```
A

The output is It's-a-me, undefined! because this.firstName is now referring to window as this. This means that window.firstName is undefined.
However! If there is a global variable firstName, window.firstName will exist! And we will get that value instead. Be careful!

141
Q

How can you tell what the value ofthiswill be for a particular function or methoddefinition?

A

You don’t know, this is determined at the time of call and not at time of definition. This means this can refer to different things depending on time of call.

142
Q

How can you tell what the value ofthisis for a particular function or methodcall?

A

Look for an object (something to the left of .)

Otherwise, it will refer to window

143
Q

What kind of inheritance does the JavaScript programming language use?

A

Prototypical inheritance

144
Q

What is a prototype in JavaScript?

A

It is an object that certain objects delegate to when they aren’t able to perform the required tasks themselves (for instance, calling a method that isn’t defined on that object yet)

145
Q

How is it possible to call methods on strings, arrays, and numbers even though those methods don’t actually exist on strings, arrays, and numbers?

A

When those methods are found to not be on any of those objects (and they are objects), JavaScript will look for the methods on the prototype of each to see if such a method exists

146
Q

If an object does not have it’s own property or method by a given key, where does JavaScript look for it?

A

It looks for the object’s prototype object, and then looks for the property/method by using the key to access the prototype

147
Q

What does thenewoperator do?

A

When combined with a constructor function, it creates an object with prototype specified by the constructor function

- Creates a blank JavaScript object
- points its `[[Prototype]]` to the constructor function's `prototype` property
- executes constructor function with given arguments (`this` inside function is now referring to the new, blank object)
- and returns the newly created object (unless the constructor function has a return statement, in which case that will be the return of the `new` expression **but don't put a return in your constructor function!**)
148
Q

What property of JavaScript functions can store shared behavior for instances created withnew?

A

prototype

149
Q

What does theinstanceofoperator do?

A

Checks if the object on the left of it has the prototype on the right of it in the left’s prototype chain (returns boolean)

150
Q

What is a “callback” function?

A

A function that is passed as an argument to an outside function and gets executed by that outside function
- f(g(x)) where g(x) is the callback function

151
Q

Besides adding an event listener callback function to an element or thedocument, what is one way to delay the execution of a JavaScript function until some point in the future?

A

Adding a timeout, setTimeout(function, delay), will execute the function after the delay in milliseconds has elapsed

152
Q

How can you set up a function to be called repeatedly without using a loop?

A

Adding an interval, setInterval(function, delay) which runs repeatedly every delay milliseconds until the interval is cleared

153
Q

What is the default time delay if you omit thedelayparameter fromsetTimeout()orsetInterval()?

A

0 milliseconds

154
Q

What dosetTimeout()andsetInterval()return?

A

An interval id that is tied to that timeout or interval and can be used to clear the interval with .clearInterval(id)
These IDs are unique to the object they are called on (global, which means a window or a worker) but two windows could have the intervals would the same IDs.

155
Q

What is the JavaScript Event Loop?

A

The event loop manages what gets run in the single-threaded JavaScript environment. It checks if the call stack is empty and if the callback queue has something in it. If so, it moves the next item from the callback queue into the call stack.

156
Q

What is different between “blocking” and “non-blocking” with respect to how code is executed?

A

Blocking is code that is executing in the call stack. On the other hand, non-blocking puts an event to “do something later” in the appropriate web API. Once that “later” comes, the “something” gets put into the callback queue to await the event loop, which will move it to the call stack when empty.