JavaScript Flashcards

1
Q

What is the purpose of variables?

A

A script will have to temporarily store the bits of information it
needs to do its job. It can store this data in variables.

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

How do you declare a variable?

A

Before you can use a variable, you need to announce that you want to use it. This involves creating the variable and giving it a name. Programmers say that you declare the variable.

var quantity;

var = variable keyword
quantity = variable name

If a variable name is more than one word, it is usually written in camelCase. This means the first word is all lowercase and any subsequent words have their first letter capitalized.

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

Once you have created a variable, you can tell it what information you would like it to store for you. Programmers say that you assign a value to the variable.

quantity = 3;

quantity = variable name
3 = variable value
= is the assignment operator

Until you have assigned a value to a variable, programmers say the value is undefined.

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, numbers, dollar sign $, or an underscore _

numbers cannot be the first character of a variable name

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

For the variable to be recognized, it needs to be entered with the same casing as it was when it was declared.

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

Strings can be used when working with any kind of text. They are frequently used to add new content into a page and they can contain HTML markup.

Strings data type consists of letters and other characters. String data type is enclosed with a pair of quotes. These can be single or double quotes, but the opening quote must match the closing quote.

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

The numeric data type handles numbers. Numbers are not only used for things like calculators; they are also used for tasks such as determining the size of the screen, moving the position of an element on a page, or setting the amount of time an element should take to fade in.

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

Boolean data types can have one of two values: true or false. To determine if something is true or false, and to tell if script should run or not in conditionals.

You can think of it a little like a light switch - it is either on or off. As you will see in Chapter 4, Booleans are helpful when determining which part of a script should run.

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

It is the assignment operator. It assigns whatever is on the right side, to whatever is on the left side.

i.e. var quantity = 3

3 is being assigned to the variable quanitity

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

Reassigning it without declaring it again, you can leave off the var

i.e.
var totalPets = 1000;
totalPets = 1001;

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

What is the difference between null and undefined?

A

Null is intentional whereas undefined hasn’t been assigned yet

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

If you do not include “labels”, it can be very confusing instead of helpful. A console log “label” is simply a short string that describes the variable or value being logged.

Since the console.log( ) method can write multiple values to the console at the same time, it’s easy to include a “label” when printing a value.

i.e.

console.log(‘typeof fullName’, typeof fullName) ->
typeof fullName: string

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, bigint, boolean, undefined, symbol, and null.

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

What data type is returned by an arithmetic operation?

A

Performs basic math, it returns a number

Addition operator is + (Adds one value to another)
Subtraction operator is - (Subtracts one value from another)
Division operator is / (Divides two values)
Multiplication operator is * (Multiplies two values using an asterisk)
Increment operator is ++ (Adds one to the current number)
Decrement operator is – (Subtracts one from the current number)
Modulus operator is % (Divides two values and returns the remainder)

Several arithmetic operations can be performed in one expression, but it is important to understand how the result will be calculated. Multiplication and division are performed before addition or subtraction. This can affect the number that you expect to see.

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

What is string concatenation?

A

There is just one string operator: the+ symbol. It is used to join the strings on either side of it.

There are many occasions where you may need to join two or more strings to create a single value. Programmers call the process of joining together two or more strings to create one new string concatenation.

For example, you might have a first and last name in two separate variables and want to join them to show a fullName. In this example, the variable called fullName would hold the string ‘Ivy Stone’.

var firstName = ‘Ivy ‘ ;
var lastName = ‘ Stone’ ;
var fullName = firstName + lastName;

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

What purpose(s) does the + plus operator serve in JavaScript?

A

Adding number values and concatenation.

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

What data type is returned by comparing two values (<, >, ===, etc)?

A

boolean

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

What does the += “plus-equals” operator do?

A

The addition assignment operator (+=) adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator. Addition or concatenation is possible.

i.e.

let a = 2;
let b = ‘hello’;

console.log(a += 3); // addition
// expected output: 5

console.log(b += ‘ world’); // concatenation
// expected output: “hello world”

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

What are objects used for?

A

Objects group together a set of variables and functions to create a model of a something you would recognize from the real world. In an object, variables and functions take on new names.

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

What are object properties?

A

If a variable is part of an object, it is called a property. Properties tell us about the object, such as the name of a hotel or the number of rooms it has. Each individual hotel might have a different name
and a different number of rooms.

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

Describe object literal notation.

A

Literal notation is the easiest and most popular way to create objects. The object is the curly braces and their contents. The object is stored in a variable called hotel, so you would refer to it as the hotel object.

var hotel = {

name: ‘Quay’,
rooms: 40,
booked: 25,
checkAvailability: function () {
return this.rooms - this.booked;
}
};

hotel = object
var = key
name: ‘Quay’, = property
rooms: 40, = property
booked: 25, = property
checkAvailability: function () { = method
return this.rooms - this.booked;
}

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

How do you remove a property from an object?

A

delete object.property

i.e. delete hotel.name;

If you just want to clear the value of a property, you could set it to a blank string.

hotel.name = ‘ ‘;

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

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

A

dot notation and square bracket syntax

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

Bracket notation

A

Allows us to put a variable in the bracket and use the value stored in that variable, as the property name

i.e.

var prop = ‘color’;
vehicle[prop] = ‘white’;

Notice how there are no quotes around [prop], because it is not a string, but a variable.

It also allows us to create or access illegal names for variables/objects

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

Primitive data types vs. Reference data types

A

They are stored differently.

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

What are arrays used for?

A

An array is a special type of variable. It doesn’t just store one value; it stores a list of values.

You should consider using an array whenever you are working with a list or a set of values that are related to each other.

Arrays are especially helpful when you do not know how many items a list will contain because, when you create the array, you do not need to specify how many values it will hold.

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

Describe array literal notation.

A

The values in the array do not need to be the same data type, so you can store a string, a number and a Boolean all in the same array.

This technique for creating an array is known as an array literal. It is usually the preferred method for creating an array. You can also write each value on a separate line:

colors = [ ‘white’,
‘black’,
‘custom’];

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

How are arrays different from “plain” objects?

A

The key for each value in an array is an index number. The index number is the location in the array.

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

What number represents the first index of an array?

A

0

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

What is the length property of an array?

A

The length property tells you how many items are in the array.

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

How do you calculate the last index of an array?

A

array.length - 1

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

What is a function in JavaScript?

A

Functions allow you to package up code for use later in your program.

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

Describe the parts of a function definition.

A

Function definitions are made of:

  • the function keyword
  • an optional name
  • zero or more parameters
  • a code block
  • an optional return statement
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

Describe the parts of a function call.

A

Functions are a special kind of object that is “callable”. Functions are called with ( ) parentheses and passed zero or more arguments.

The function name followed by the arguments replacing the parameters in ( )

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

When comparing them side-by-side, what are the differences between a function call and a function definition?

A

The call is just the name and arguments (within parentheses)

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

What is the difference between a parameter and an argument?

A

Parameters are placeholders for arguments. The key thing to remember about parameters and arguments is that when we define a function, we declare parameters and that when we call a function, we pass it arguments.

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

Why are function parameters useful?

A

They let us pass data into the function and to variables that are only locally accessible to them

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

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

A
  1. Causes the function to produce a value we can use in our program.
  2. Prevents any more code in the function’s code block from being run.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

Are variables within a function accessible?

A

No, variables defined within a function are inaccessible from the outside. However, they can access variables on the outside of the function.

(You cannot view it from the outside, but you can look outside - like a car’s tinted window)

If they aren’t defined as a variable, then they can be accessed from the outside. They would be noted as an auto global.

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

Why do we log things to the console?

A

The JavaScript console is a debugging tool. It is where the browser prints errors and warnings as they occur in your JavaScript code. The console is a crucial learning tool and should be used as much as possible to play with and learn about JavaScript. You should be using console.log ( ) and checking the console output frequently, so be sure to include “labels” with your console.log ( )s.

The user does not see the console. Anything you print the console, the end user will not see it, unless you add it to the DOM somewhere.

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

What is a method?

A

A method is a function which is a property of an object. There are two kinds of methods: instance methods which are built-in tasks performed by an object instance, or static methods which are tasks that are called directly on an object constructor.

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

How is a method different from any other function?

A

A method is a property of an object (assigned to the property of an object)

a method can be turned into a function if it is assigned to a property of an object

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

How do you remove the last element from an array?

A

the pop method

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

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

A

Math.floor method. The floor method of the Math object

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

How do you generate a random number?

A

Math.random method.

The random method of the Math object (the range of numbers generated is 0-1)

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

How do you delete an element from an array?

A

The splice method. It needs start and delete count parameters to know index to delete and how many to delete from there.

library.splice(1, 1)

Start at 1, delete 1

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

How do you append an element to an array?

A

The push method - the quickest way to append an element to an array

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

How do you break a string up into an array?

A

The split method

var fullName = ‘Lisa Nguyen’

It will split Lisa and Nguyen

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

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

A

They don’t, they can create new strings stored to new variables, you can check by console logging them (the original variable, if the console log shows the original string, that means that the original string was not modified) and MDN. There is no way to change an existing string.

Avoid using string methods that have a trash icon because they are deprecated (on MDN website)

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

Roughly how many string methods are there according to the MDN Web docs?

A

50

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

Is the return value of a function or method useful in every situation?

A

No, you don’t always need a return value when calling methods (splice, push, unshift) because if you are using it to modify something, you don’t need to return it

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

Roughly how many array methods are there according to the MDN Web docs?

A

80+

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

What three-letter acronym should you always include in your Google search about a JavaScript method or CSS property?

A

MDN

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

How do you join a split string together?

A

Using the join method. Join can be used to remove white space.

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

What is JavaScript also known as?

A

ECMA Script. This is used my developers who create the engines that run JavaScript.

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

Give 6 examples of comparison operators.

A

< less than
> greater than
== is equal to
!= is not equal to
=== strictly equal to
!== strictly not equal to
>= greater than or equal to
<= less than or equal to

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
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
58
Q

What is the purpose of an if statement?

A

The if statement evaluates (or checks) a condition. If the condition evaluates to true, any statements in the subsequent code block are executed.

If the condition resolves to false, the statements in that code block are not run. (The script continues to run from the end of the next code block.)

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

Is else required in order to use an if statement?

A

It is not required to use an if statement.

The if ….else statement checks a condition. If it resolves to true, the first code block is executed. If the condition resolves to false, the second code block is run instead.

i.e.

if (score >= 50) {
congratulate();
}
else {
encourage();
}

If you require code to run only when the statement returns true (and do nothing else if false) then an else statement is not needed.

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

Describe the syntax (structure) of an if statement.

A

key word, condition, opening curly brace (start of code block), code to be executed, closing curly brace (end of code block)

if ( ) {

};

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

What are the three logical operators?

A

&& and
|| or
!= not

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

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

A

using logical operators

If both of them need to be true, use &&

If only one of them need to be true, use or ||

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

What is the purpose of a loop?

A

Loops check a condition. If it returns true, a code block will run. Then the condition will be checked again and if it still returns true, the code block will run again. It repeats until the condition returns false. There are three common types of loops:

for, while, do while

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

What is the purpose of a condition expression in a loop?

A

The purpose is to end the loop. When the condition is no longer true, the loop ends. The script moves to the next line of code. Giving conditions for the code to be executed and where to stop.

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

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

A

Each time the loop runs

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

When does the condition expression of a while loop get evaluated?

A

before each iteration

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

When does the initialization expression of a for loop get evaluated?

A

before anything else (the first time the for loop runs)

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

When does the condition expression of a for loop get evaluated?

A

before each loop iteration and after the initialization expression

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

When does the final expression of a for loop get evaluated?

A

the end of each loop iteration (after the work is completed)

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

Besides a return statement, which exits its entire function block, which keyword exits a loop before its condition expression evaluates to false?

A

a break statement will break out of the loop but not out of a function

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

What does the ++ increment operator do?

A

It is the incremental operator adding one to the counter, and assigns it to the i variable.

it substitute first and then adds after

i.e.

var a = 1

a++ will return 1

logging a will return 2

if you do ++a, it will increment the value first, and then substitute it

++a will return 3 and logging a will return 3

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

How do you iterate through the keys of an object?

A

With a For In Loop

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

Why do we log things to the console?

A

The JavaScript console is a debugging tool. It is where the browser prints errors and warnings as they occur in your JavaScript code. The console is a crucial learning tool and should be used as much as possible to play with and learn about JavaScript. You should be using console.log ( ) and checking the console output frequently, so be sure to include “labels” with your console.log ( )s.

The user does not see the console. Anything you print the console, the end user will not see it, unless you add it to the DOM somewhere.

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

What is a “model”?

A

When the browser loads a web page, it creates a model of the page in memory. The model is called a DOM tree, and it is stored in the browsers’ memory.

It is a representation of something.

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

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

A

Document Object - The current web page (the HTML document) loaded into each window is modelled using a document object. The title property of the document object tells you what is between the opening < title > and closing
< / title > tag for that web page.

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

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

A

Object for the document, so the whole entire page since it is an object

77
Q

What is a DOM Tree?

A

The DOM tree is a model of a webpage. It is stored in the browsers’ memory.

78
Q

Give two examples of document methods that retrieve a single element from the DOM.

A

getElementById(‘id’) <– This is faster because it does not have to search the document

querySelector(‘css selector’)

79
Q

Give one example of a document method that retrieves multiple elements from the DOM at once.

A

getElementByClassName(‘class’)
getElementByTagName(‘tagName’)
querySelectorAll(‘css selector’)

80
Q

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

A

You often see element nodes stored in a variable for use later in the script. If your script needs to use the same element(s) more than once, you can store the location of the element(s) in a variable.

This saves the browser looking through the DOM tree to find the same element(s) again. It is known as caching the selection.

The variables store a reference to the object in the DOM tree (It is storing the location of the node).

81
Q

What console method allows you to inspect the properties of a DOM element object?

A

console.dir ( )

82
Q

Why would a < script > tag need to be placed at the bottom of the HTML content instead of at the top?

A

The browser needs to parse all of the elements in the HTML page before the JavaScript code can access them.

83
Q

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

A

Selectors - A string containing one or more selectors to match. This string must be a valid CSS selector string; if it isn’t, a SyntaxError exception is thrown.

Returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

84
Q

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

A

selectors
A string containing one or more selectors to match against. This string must be a valid CSS selector string; if it’s not, a SyntaxError exception is thrown.

Returns a static (not live) NodeList representing a list of the document’s elements that match the specified group of selectors.

85
Q

What is the purpose of events and event handling?

A

Events are fired to notify code of “interesting changes” that may affect code execution. These can arise from user interactions such as using a mouse or resizing a window, changes in the state of the underlying environment (e.g. low battery or media events from the operating system), and other causes.

Event handlers let you indicate which event you are waiting for on any particular element.

When the user interacts with the HTML on a web page, there are three steps involved in getting it to trigger some JavaScript code.
Together these steps are known as event handling.

  1. Select the element node(s) you want the script to respond to. For example, if you want to trigger a function when a user clicks on a specific link, you need to get the DOM node for that link element. You do this using a DOM query (see Chapter 5).
  2. Indicate which event on the selected node(s) will trigger the response. Programmers call this binding an event to a DOM node. The previous two pages showed a selection of the popular events that you can monitor for.
  3. State the code you want to run when the event occurs. When the event occurs, on a specified element, it will trigger a function. This may be a named or an anonymous function.
86
Q

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

A

No, because you don’t necessarily need to include a parameter.

Event or e is the most common parameter to pass when using a callback function.

87
Q

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

A

addEventListener method

88
Q

What is a callback function?

A

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

89
Q

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

A

event object

90
Q

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

A

The element that dispatches the event.

The target is always going to represent the element that was interacted with.

The read-only target property of the Event interface is a reference to the object onto which the event was dispatched. It is different from Event.currentTarget when the event handler is called during the bubbling (traveling back up the html document) or capturing phase (traveling down the html document) of the event.

The event.target property can be used in order to implement event delegation.

I would check MDN to get more information about it.

91
Q

What is the difference between these two snippets of code?
element.addEventListener(‘click’, handleClick)

element.addEventListener(‘click’, handleClick( ))

A

The first EventListener is passing a listener event and a function name (calling the function and passing it as a parameter - callback function) whereas the second one is passing a listener event and a function that we are calling.

If we call the function as an argument, we are passing undefined into the function so it returns nothing –>

element.addEventListener(‘click’, handleClick( ))

92
Q

What is the className property of element objects?

A

The className property of the Element interface gets and sets the value of the class attribute of the specified element.

The name className is used for this property instead of class because of conflicts with the “class” keyword in many languages which are used to manipulate the DOM.

93
Q

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

A

Using the className property of the Element interface with an assignment operator. The value of the class attribute of the specified element will be updated.

94
Q

What is the textContent property of element objects?

A

The textContent property of the Node interface represents the text content of the node and its descendants.

textContent gets the content of all elements, including and elements. In contrast, innerText only shows “human-readable” elements.

textContent returns every element in the node. In contrast, innerText is aware of styling and won’t return the text of “hidden” elements.

Differences from innerHTML
Element.innerHTML returns HTML, as its name indicates. Sometimes people use innerHTML to retrieve or write text inside an element, but textContent has better performance because its value is not parsed as HTML.

95
Q

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

A

Using the textContent property of the Node interface with an assignment operator

96
Q

Is the event parameter of an event listener callback always useful?

A

i.e. hotButton.addEventListener(‘click’, function (event) { } )

It’s not always useful, it’s not always the case that we have to use parameters

97
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

More complicated because we wouldn’t be able to compare it to a number to assign the hotButton the appropriate CSS class name

We would have to access the textContent from the DOM and manipulate the string

98
Q

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

A

So you can access it later / have easy access to it

99
Q

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

A

the focus event

100
Q

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

A

the blur event

101
Q

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

A

the input event

102
Q

What event is fired when a user clicks the “submit” button within a < form >?

A

the submit event

103
Q

What does the event.preventDefault( ) method do?

A

The preventDefault( ) method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.

It prevents the default behavior.

104
Q

What does submitting a form without event.preventDefault( ) do?

A

The browser will automatically reload the page with the form’s values in the URL

105
Q

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

A

The HTMLFormElement property elements returns an HTMLFormControlsCollection listing all the form controls contained in the element.

Elements property

106
Q

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

A

The HTMLInputElement interface provides special properties and methods for manipulating the options, layout, and presentation of elements.

value (property)
string: Returns / Sets the current value of the control. If the user enters a value different from the value expected, this may return an empty string.

107
Q

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

A

It would be difficult to find the error in your code/debugging it if you had already written a lot of code

ALWAYS CHECK YOUR STEPS! Checking as you go!

108
Q

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

A

To catch errors and debug

109
Q

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

A

It only creates the element, it does not add the element to the page yet

110
Q

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

A

appendChild( ) method

or append( ) method

111
Q

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

A

setAttribute(name, value)

name and value are passed as arguments

Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.

112
Q

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

A
  1. Create the element with createElement( ) method
    -This element node is stored in a variable, when the element node is created, it is not yet part of the DOM tree.
  2. Give it content with createTextNode ( ) method
    - The node is stored in a variable, it can be added to the element node using the appendChild ( ) method. This provides the content for the element, although you can skip this step if you want to attach an empty element to the DOM tree.
  3. Add it to the DOM with appendChild( ) method
    - Now that you have your element, you can add it to the DOM tree using this method. It allows you to specify which element you want this node added to, as a child of it.
113
Q

What is the textContent property of an element object for?

A

The textContent property of the Node interface represents the text content of the node and its descendants.

It’ll create the node and add the text content to it.

114
Q

Name two ways to set the class attribute of a DOM element.

A

element.setAttribute( )

element.className( )

divThirdColumn.classList.add(‘column-third’)

115
Q

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

A
  1. Being able to access the function again if you need it for future use
  2. You only have to change the code in one place if changes are needed in the future (like adding more functionality, fixing a bug, etc.)
  3. It helps keep your code more organized because similar or related logic can be kept in one place
116
Q

What is the event.target?

A

The read-only target property of the Event interface is a reference to the object onto which the event was dispatched. It is different from Event.currentTarget when the event handler is called during the bubbling or capturing phase of the event.

117
Q

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

A

Because of event flow, this happens because of event bubbling and event capturing

event bubbling - the event starts at the most specific node and flows outwards to the least specific one. This is the default type of event flow with very wide browser support.

event capturing - the event starts at the least specific node and flows inwards to the most specific one. This is not supported in IE 8 and earlier.

the final parameter in the addEventListener( ) method lets you choose the direction to trigger events:
- true = capturing phase
- false = bubbling phase

118
Q

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

A

The tagName read-only property of the Element interface returns the tag name of the element on which it’s called.

For example, if the element is an < img >, its tagName property is “IMG” (for HTML documents; it may be cased differently for XML/XHTML documents).

119
Q

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

A

It takes selectors as its argument and returns the closest ancestor element or itself, which matches the selectors. If there are no such element, it returns null.

120
Q

How can you remove an element from the DOM?

A

The Element.remove( ) method removes the element from the DOM.

121
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

Adding the clickable DOM elements to the element that already has an event listener as its descendant or ancestor (event.target)

Add an event listener to the parent element, and it would work for all descendant elements

122
Q

What is the affect of setting an element to display: none?

A

Using a display value of none on an element will remove it from the accessibility tree. This will cause the element and all its descendant elements to no longer be announced by screen reading technology.

If you want to visually hide the element, a more accessible alternative is to use a combination of properties to remove it visually from the screen but keep it parsable by assistive technology such as screen readers.

123
Q

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

A

The matches( ) method of the Element interface tests whether the element would be selected by the specified CSS selector.

It takes selectors (a string containing valid CSS selectors) as an argument and

returns true if the Element matches the selectors, otherwise, it returns false

124
Q

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

A

The getAttribute( ) method of the Element interface returns the value of a specified attribute on the element.

Element.getAttribute( )

125
Q

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

A

You should log every time you have a new variable, whenever you’re setting something new to check if it is returning what you are expecting

EVERY STEP!

126
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 require its own addEventListener

127
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

Incorporate some type of conditional block, one check for each of the possible element that it could be

128
Q

What is JSON?

A

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa). You’ll come across it quite often, so in this article we give you all you need to work with JSON using JavaScript, including parsing JSON so you can access data within it, and creating JSON.

JSON is an extremely common data interchange format used to send and store information in computer systems. Before JSON, XML was a popular data interchange format, but JSON’s simplicity and readability has made it the preferred format.

JSON exists as a string — useful when you want to transmit data across a network. It needs to be converted to a native JavaScript object when you want to access the data. This is not a big issue — JavaScript provides a global JSON object that has methods available for converting between the two.

129
Q

What are serialization and deserialization?

A

Serialization is the process of turning an object in memory into a stream of bytes so you can do stuff like store it on disk or send it over the network.

Deserialization is the reverse process: turning a stream of bytes into an object in memory.

130
Q

Why are serialization and deserialization useful?

A

Serialization is useful because you can transfer objects to main memory or across network, and deserialize them again later.

131
Q

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

A

JSON.stringify( )

132
Q

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

A

JSON.parse( )

133
Q

How do you store data in localStorage?

A

localStorage.setItem(‘myCat’, ‘Tom’);

The setItem( ) method of the Storage interface, when passed a key name and value, will add that key to the given Storage object, or update that key’s value if it already exists.

setItem(keyName, keyValue)

134
Q

How do you retrieve data from localStorage?

A

The getItem( ) method of the Storage interface, when passed a key name, will return that key’s value, or null if the key does not exist, in the given Storage object.

135
Q

What data type can localStorage save in the browser?

A

JSON Strings

136
Q

When does the ‘beforeunload’ event fire on the window object?

A

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point.

137
Q

What is a method?

A

A method is a function which is a property of an object. There are two kinds of methods: instance methods which are built-in tasks performed by an object instance, or static methods which are tasks that are called directly on an object constructor.

138
Q

How can you tell the difference between a method definition and a method call?

A

A method definition defines the method with a code block/function, and a method call only calls the method’s name on a certain object using ( )

139
Q

Describe method definition syntax (structure).

A

const obj = {
foo( ) {
return ‘bar’;
}
};

140
Q

Describe method call syntax (structure).

A

object.method( )

141
Q

How is a method different from any other function?

A

A method, like a function, is a set of instructions that perform a task. The difference is that a method is associated with an object, while a function is not.

142
Q

What is the defining characteristic of Object-Oriented Programming?

A

Objects can contain both data (as properties) and behavior (as methods).

143
Q

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

A
  • Abstraction
  • Encapsulation
  • Inheritance
  • Polymorphism
144
Q

What is “abstraction”?

A

The process of removing or generalizing physical, spatial, or temporal details[2] or attributes in the study of objects or systems to focus attention on details of greater importance;[3] it is similar in nature to the process of generalization;

the creation of abstract concept-objects by mirroring common features or attributes of various non-abstract objects or systems of study[3] – the result of the process of abstraction.

The most important part of the term “abstraction” boils down to being able to work with (possibly) complex things in simple ways. You are already familiar with abstractions, though you may not have thought of them this way yet. Here are just a couple of everyday examples of abstractions.

A light switch
You usually flip a light switch on or off to control the light in a room. The reality is that you are closing an electrical circuit that connects to a mains breaker somewhere in your home so that 120 volts at 15 amps goes through a light bulb. But to you, you are “turning on the lights”.

145
Q

What does API stand for?

A

An application programming interface (API) is a way for two or more computer programs to communicate with each other.

146
Q

What is the purpose of an API?

A

One purpose of APIs is to hide the internal details of how a system works, exposing only those parts a programmer will find useful and keeping them consistent even if the internal details later change. An API may be custom-built for a particular pair of systems, or it may be a shared standard allowing interoperability among many systems.

The term API is often used to refer to web APIs, which allow communication between computers that are joined by the internet. There are also APIs for programming languages, software libraries, computer operating systems, and computer hardware. APIs originated in the 1940s, though the term did not emerge until the 1960s and 1970s. Recent developments in utilizing APIs have led to the rise in popularity of microservices, which are ultimately loosely coupled services accessed through public APIs.

147
Q

What is this in JavaScript?

A

this is an implicit parameter of all JavaScript functions

148
Q

What does it mean to say that this is an “implicit parameter”?

A

this is different from explicit parameters: it’s an implicit parameter, meaning that it is available in a function’s code block even though it was never included in the function’s parameter list or declared with var

149
Q

When is the value of this determined in a function; call time or definition time?

A

the value of this is determined at call time.
the value of this can be recognized as “the object to the left of the dot” when the function is called (as a method).

150
Q

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

A

character variable

151
Q

Given the above character object, what is the result of the following code snippet? Why?
character.greet( );

A

‘It's-a-me, ‘ + this.firstName + ‘!’;

The greet property has a value of an anonymous function with a message in a variable

152
Q

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

A

‘It's-a-me, ‘ + undefined

It would come out as undefined because there’s no firstName property of the window

hello is to the left of the ( ) and hello does not have a define object, it will default to the window and the window does not have + this.firstName property

153
Q

How can you tell what the value of this will be for a particular function or method definition?

A

You cannot tell based on the definition, you can only tell what is being called

154
Q

How can you tell what the value of this is for a particular function or method call?

A

the value of this can be recognized as “the object to the left of the dot” when the function is called (as a method).

155
Q

What kind of inheritance does the JavaScript programming language use?

A

A core concept in Object-Oriented Programming is inheritance. The concept is given the name “inheritance” because it is similar to genetics. Parent organisms give traits to their offspring through their DNA. JavaScript includes a specific kind of inheritance known as prototype-based (or prototypal) inheritance. JavaScript objects give certain behaviors (methods) or data (properties) to other objects.

Prototypal inheritance in JavaScript a fairly simple concept (especially compared to this). The ultimate goal is to move properties and methods that we’d like to reuse into a “prototype” object and then tell other objects to simply delegate (verb) to that “prototype” object when they aren’t able to perform the required tasks themselves.

156
Q

What is a prototype in JavaScript?

A

As mentioned before, a JavaScript prototype is simply an object that contains properties and (predominantly) methods that can be used by other objects.

157
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

Instead, those methods are defined on a “prototype” object and arrays simply borrow those methods when they’re needed.

158
Q

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

A

The prototype chain

159
Q

What does the new operator do?

A

The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

  1. Creates a blank, plain JavaScript object. For convenience, let’s call it newInstance.
  2. Points newInstance’s [[Prototype]] to the constructor function’s prototype property, if the prototype is an Object. Otherwise, newInstance stays as a plain object with Object.prototype as its [[Prototype]]. (Binding whatever is on the prototype property of that object to the proto property of the new object)

Note: Properties/objects added to the constructor function’s prototype property are therefore accessible to all instances created from the constructor function.

  1. Executes the constructor function with the given arguments, binding newInstance as the this context (i.e. all references to this in the constructor function now refer to newInstance).
  2. If the constructor function returns a non-primitive, this return value becomes the result of the whole new expression. Otherwise, if the constructor function doesn’t return anything or returns a primitive, newInstance is returned instead. (Normally constructors don’t return a value, but they can choose to do so to override the normal object creation process.) (NEVER return anything from your constructor function, it returns the object)
160
Q

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

A

prototype property

161
Q

What does the instanceof operator do?

A

The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value. Its behavior can be customized with Symbol.hasInstance.

162
Q

What is a “callback” function?

A

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

163
Q

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

A

setTimeout( ) is a global function, so you can call it directly by name without any object to the left of the dot. e.g. setTimeout(func, delay).

164
Q

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

A

The setInterval( ) function, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.

This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval( ).

165
Q

What is the default time delay if you omit the delay parameter from setTimeout( ) or setInterval( )?

A

The time, in milliseconds that the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute “immediately”, or more accurately, the next event cycle.

Defaults to 0 if not specified.

166
Q

What do setTimeout( ) and setInterval( ) return?

A

setTimeout ( ) = The returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout(). This value can be passed to clearTimeout() to cancel the timeout.

setInterval ( ) = The returned intervalID is a numeric, non-zero value which identifies the timer created by the call to setInterval( ); this value can be passed to clearInterval( ) to cancel the interval.

167
Q

What is AJAX?

A

Ajax is a technique for loading data into part of a page
without having to refresh the entire page. The data is often sent in a format called JavaScript Object Notation (or JSON).

Ajax allows you to request data from a server and load it without having to refresh the entire page.

168
Q

What does the AJAX acronym stand for?

A

Asynchronous JavaScript And XML

169
Q

Which object is built into the browser for making HTTP requests in JavaScript?

A

XMLHttpRequest object

170
Q

What event is fired by XMLHttpRequest objects when they are finished loading the data from the server?

A

The load event

171
Q

Bonus Question: An XMLHttpRequest object has an addEventListener( ) method just like DOM elements. How is it possible that they both share this functionality?

A

prototypal inheritance

172
Q

What is a code block? What are some examples of a code block?

A

{ }
Code blocks are denoted by curly braces.

i.e. if else, for, do while, while, has a code block

173
Q

What does block scope mean?

A

inside of a code block { }

174
Q

What is the scope of a variable declared with const or let?

A

it is block-scoped

175
Q

What is the difference between let and const?

A

Like the let keyword, the const keyword declares blocked-scope variables. However, the block-scoped variables declared by the const keyword can’t be reassigned.

The variables declared by the let keyword are mutable. It means that you can change their values anytime.

However, variables created by the const keyword are “immutable”. In other words, you can’t reassign them to different values.

Unlike the let keyword, you need to initialize the value to the variable declared by the const keyword.

176
Q

Why is it possible to .push() a new value into a const variable that points to an Array?

A

Because it is possible to change the property/value of an object but not assign a value to the constant

177
Q

How should you decide on which type of declaration to use?

A

Whether or not you want the object to be immutable or mutable

178
Q

What is the syntax for writing a template literal?

A

you create a template literal by wrapping your text in backticks (`) as follows:

let simple = This is a template literal;

To instruct JavaScript to substitute a variable and expression, you place the variable and expression in a special block as follows:

${variable_name}

179
Q

What is “string interpolation”?

A

String formatting: the ability to substitute part of the string for the values of variables or expressions.

180
Q

What is destructuring, conceptually?

A

Assigns properties of an object to individual variables.

181
Q

What is the syntax for Object destructuring?

A

ES6 introduces the object destructuring syntax that provides an alternative way to assign properties of an object to variables:

let { firstName: fname, lastName: lname } = person;

In this example, the firstName and lastName properties are assigned to the fName and lName variables respectively.

In this syntax:

let { property1: variable1, property2: variable2 } = object;

The identifier before the colon (:) is the property of the object and the identifier after the colon is the variable.

182
Q

What is the syntax for Array destructuring?

A

function getScores( ) {
return [70, 80, 90];
}

let [x, y, z] = getScores( );

console.log(x); // 70
console.log(y); // 80
console.log(z); // 90

The variables x, y and z will take the values of the first, second, and third elements of the returned array.

Note that the square brackets [ ] look like the array syntax but they are not.

183
Q

How can you tell the difference between destructuring and creating Object/Array literals?

A

When are destructing, the property/values are on the left side of the variable/equal sign

When creating object/array literals, the properties/values are on the right of the equal side

184
Q

What is the syntax for defining an arrow function?

A

let add = (x, y) => x + y;

185
Q

When an arrow function’s body is left without curly braces, what changes in its functionality?

A

Return keyword is not needed, it returns the result of the expression

However, if you use a statement, you must wrap it inside a pair of curly braces as in the following example:

let except = msg => {
throw msg;
};

186
Q

How is the value of this determined within an arrow function?

A

Unlike an anonymous function, an arrow function captures the this value of the enclosing context instead of creating its own this context.

It is determined by the parent scope.

187
Q

What is the JavaScript Event Loop?

A

It allows JavaScript to run asynchronous events in sequential order

188
Q

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

A

Blocking = a code that is being run and preventing other code from being ran (the stack/queue will prevent other code from running)

Non-blocking is when the code is being accessed later (async) so that it is not blocking (it gets pushed to the side and the rest of the code keeps doing its thing- once it’s done, it has some kind of callback function that goes back into the call stack)