Javascript Flashcards

(183 cards)

1
Q

What is the purpose of variables?

A

to store information to be referenced/accessed later

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

How do you declare a variable?

A

use the keyword “var”

  • var newVariable
  • (also use const/let)
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

put an equals sign after the variable you want to initialize, and then put the value after the equals sign
e.g. newVariable = ‘new value’

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
  • variable must begin with: letter, $, or _. after that, numbers can be used as well
  • cannot use keywords
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

capital and lower casing matter

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 a sequence of characters (text)

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

gives us a numeric value as a constant to work with

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

indicates two possible values (true/false)

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

assigns a value to the variable that’s on the left of the operator

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

varName = ‘new updated value’

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 an object with the assigned value of “no value”
  • undefined is a type, where the variable is undeclared or undefined (not been given a value)
  • in your code, you should not use “undefined”. undefined is generally used for debugging
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

so that you know the context for the printed value

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

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

number

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

What is string concatenation?

A

combination of 2+ values

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 or concatenation

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

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

A

adds the right-hand value onto the left-hand value and assigns it to the left-hand value
—> (x += 5) is the same as (x = x+5)

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

What are objects used for?

A

used to hold a collection of properties and methods

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

What are object properties?

A

a name-value pair that tells us more about the object

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

Describe object literal notation

A
objectName = {
	name: value,
	name2: value2,
	name3: value3
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How do you remove a property from an object?

A

delete objectName.propertyName

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

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

A

dot notation, bracket notation

  • dot notation is very literal. property identifiers cannot be a variable, or start w a number, or have spaces, etc
  • bracket notation has fewer limitations. property identifiers can be variables
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What are arrays used for?

A

arrays store a collection of elements of the same data type

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

Describe array literal notation.

A

var newArray = []

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
How are arrays different from "plain" objects?
- plain objects have properties - arrays store lists of data of the same type - arrays have a numeric key [a, b, c] is {0: a, 1: b, 2: c}
26
What number represents the first index of an array?
0
27
What is the length property of an array?
tells you how many elements are in the array
28
How do you calculate the last index of an array?
array.length-1
29
What is a function in JavaScript?
a block of code that does something or calculates something
30
Describe the parts of a function definition.
- the function keyword - an optional name - zero or more parameters - a code block - an optional return statement ``` function newFunction(parameter1, parameter2) { xyz action return xyz } ```
31
Describe the parts of a function call.
functionName(arguments)
32
When comparing them side-by-side, what are the differences between a function call and a function definition?
- function definition states what action the function will perform w its arguments - function call invokes the function to perform the action
33
What is the difference between a parameter and an argument?
- parameter is a placeholder for where arguments will be applied - argument is the actual value that will be going into the function
34
Why are function parameters useful?
- states all the information that will be needed to run the function - allows you to reuse code with different data
35
What two effects does a return statement have on the behavior of a function?
- causes the function to produce a value | - exits the function
36
Why do we log things to the console?
console logging helps developers keep track of their code, making sure the outputs are correct
37
What is a method?
a function stored as a property of an object
38
How is a method different from any other function?
- a method acts on the data of the object it belongs to | - a function is standalone
39
How do you remove the last element from an array?
arrayName.pop()
40
How do you round a number down to the nearest integer?
Math.floor(number)
41
How do you generate a random number?
Math.random() - multiply it by a number you want the range of - the formula==>Math.floor(Math.random() * (end - start) +1) + start
42
How do you delete an element from an array?
arrayName.splice(start index, # of elements to be deleted, item1 to be added, item2, ...) -only the start index is required as an argument
43
How do you append an element to an array?
arrayName.push(newElement)
44
How do you break a string up into an array?
arrayName.split('')
45
Do string methods change the original string? How would you check if you weren't sure?
- strings are immutable - string methods do not change the original string (they create new outputs) - you can check by console logging the string value
46
Roughly how many string methods are there according to the MDN Web docs?
30-ish
47
Is the return value of a function or method useful in every situation?
no, sometimes the function or method is used just to perform an action
48
Roughly how many array methods are there according to the MDN Web docs?
36
49
What three-letter acronym should you always include in your Google search about a JavaScript method or CSS property?
MDN
50
How do you pre-pend an element to an array?
arrayName.unshift()
51
Give 6 examples of comparison operators.
==, !=, >, =, <=
52
What data type do comparison expressions evaluate to?
boolean
53
What is the purpose of an if statement?
sets a condition to help the computer decide which lines of code should be run next
54
Is 'else' required in order to use an if statement?
no
55
Describe the syntax (structure) of an if statement.
if (condition) { code to be run if condition is met }
56
What are the three logical operators?
and && or || not !
57
How do you compare two different expressions in the same condition?
(expression1) &&/|| (expression2)
58
What is the purpose of a loop?
-run the same block of code a certain amount of time
59
What is the purpose of a condition expression in a loop?
lets the computer know when to stop the loop
60
What does "iteration" mean in the context of loops?
represents each instance of the code block in the curly brackets of the loop being run
61
When does the condition expression of a while loop get evaluated?
after every iteration
62
When does the initialization expression of a for loop get evaluated?
once, at the beginning
63
When does the condition expression of a for loop get evaluated?
the condition gets checked at the beginning of every iteration, following initialization
64
When does the final expression of a for loop get evaluated?
after the code block is run
65
Besides a return statement (which exits its entire function block) which keyword exits a loop before its condition expression evaluates to false?
break
66
What does the ++ increment operator do?
adds +1 to the variable
67
How do you iterate through the keys of an object?
"for in" loop
68
when should you use a for loop vs a while loop vs a do while loop?
- for loop: need to run the code a specific number of times (condition is a counter) - while loop: need to run the code an unknown number of times (condition is not a counter) - do while loop: similar to a 'while loop' but will always run the statements inside curly brackets at least once, even if the condition is false
69
Why do we log things to the console?
for debugging purposes so that we know what our output is
70
What is a "model"?
- a representation of the actual thing | - in the DOM, a model is the data representation of all the objects that make up a web document
71
Which "document" is being referred to in the phrase Document Object Model?
-web document: the html page
72
What is the word "object" referring to in the phrase Document Object Model?
-javascript object
73
What is a DOM Tree?
the data representation of all the objects that make up a web document where there is a parent stem that branches into child branches
74
Give two examples of document methods that retrieve a single element from the DOM.
- getElementById('id-name') - querySelector('css selector') *the best one to use is querySelector
75
Give one example of a document method that retrieves multiple elements from the DOM at once.
- getElementsByClassName('class') - getElementsByTagName('tagName') - querySelectorAll('css selector') *the best one to use is querySelectorAll
76
Why might you want to assign the return value of a DOM query to a variable?
so you can re-use that reference in your javascript code without js having to search thru the entire html document
77
What console method allows you to inspect the properties of a DOM element object?
console.dir('element')
78
Why would a tag need to be placed at the bottom of the HTML content instead of at the top?
the browser needs to finish loading all the elements in the html page before js can access them
79
What does document.querySelector() take as its argument and what does it return?
it takes in a css selector and returns the first element in the dom that matches the selector
80
What does document.querySelectorAll() take as its argument and what does it return?
it takes in a css selector and returns all the elements in the dom that match the selector
81
What is the purpose of events and event handling?
allows us to execute code only when a certain event is happening The handler is simply a function which does something (it's executed) when the event happens. The handler function, by default, when executed is passed the event object (that was created when the event/action you are interested in happened) as an argument.
82
Are all possible parameters required to use a JavaScript method or function?
-no -ie. eventTarget.addEventListener takes in up to 4 parameters, but you really only use the first two eventTarget.addEventListener(type, listener, useCapture, wantsUntrusted)
83
What method of element objects lets you set up a function to be called when a specific type of event occurs?
.addEventListener('click', handleClick) 'click' is the action to listen for handleClick is your function
84
What is a callback function?
a function passed into another function as an argument to be executed later
85
What object is passed into an event listener callback when the event fires?
event object (this will be generated when the event fires. will generate properties such as "event.target", "event.altKey", etc)
86
What is the event.target? If you weren't sure, how would you check? Where could you get more information about it?
- event.target is where the element on which the event happened originated from (its reference) - you can check by console logging "event.target" - or look it up on MDN
87
What is the difference between these two snippets of code? element. addEventListener('click', handleClick) element. addEventListener('click', handleClick())
- the variable handleClick is held as a callback function (browser will call the function) - the function handleClick() is called immediately (you are the one calling the function)
88
What is the difference between event handler and event listener?
- event handler: defines what to do when the function is called (when the event occurs) - event listener: uses the event handler (callback function) to do something when the event occurs
89
What is the className property of element objects?
sets/updates/returns the class name of an element
90
How do you update the CSS class attribute of an element using JavaScript?
$button.className = 'newClassName'
91
What is the textContent property of element objects?
represents the text content of the node and also the text content of its descendents (differs from "innerText" which only represents "human-readable" elments)
92
How do you update the text within an element using JavaScript?
$button.textContent = 'new text content'
93
Is the event parameter of an event listener callback always useful?
no, it's useful when the handler function needs to know about the event that happened
94
Why is storing information about a program in variables better than only storing it in the DOM?
if the information is only stored within the DOM, js would have to search other places (like the entire html document) to find it
95
Does the document.createElement() method insert a new element into the page?
no, it's stored in a variable and not added to DOM until you use appendChild()
96
How do you add an element as a child to another element?
appendChild()
97
What do you pass as the arguments to the element.setAttribute() method?
element. setAttribute(name, value) - name: a DOMString specifying the name of the attribute - value: a DOMString containing the attribute's value
98
What steps do you need to take in order to insert a new element into the page?
1. create the element - createElement() 2. give it content (optional) - createTextNode() 3. add it to the DOM - appendChild()
99
What is the textContent property of an element object for?
return or change the text content of the element
100
Name two ways to set the class attribute of a DOM element.
- element.className = newClassName | - element.setAttribute('class', 'value')
101
What are two advantages of defining a function to do or create something (like the work of creating a DOM tree)?
- you can reuse the function - makes the program easier to read because you can organize it into smaller chunks - need the DOM tree in multiple sections
102
What property of form a control object gets and sets its value?
value
103
What property of a form element object contains all of the form's controls.
elements
104
What does submitting a form without event.preventDefault() do?
prevents the form from submitting
105
What does the event.preventDefault() method do?
prevents the default event from happening (checkboxes go unchecked, form submissions do not refresh the page, etc)
106
What event is fired when a user clicks the "submit" button within a ?
submit
107
What event is fired as a user changes the value of a form control?
input
108
What event is fired when a user's cursor leaves a form control?
blur
109
What event is fired when a user places their cursor in a form control?
focus
110
What is the event.target?
where the event occurred (the target object)
111
Why is it possible to listen for events on one element that actually happen its descendent elements?
event is carried forward to each level of its anscestral chain
112
What DOM element property tells you what type of element it is?
event.target.tagName | nodeName could also work
113
What does the element.closest() method take as its argument and what does it return?
targetElement.closest(selectors) -ex. $button.closest('.div-class') it returns the DOM element that is closest to the chain that matches the selector
114
How can you remove an element from the DOM?
element.remove();
115
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?
add it to the closest parent element that contains all the elements (event delegation)
116
What is the effect of setting an element to display: none?
removes it from the document flow and causes the element and all of its children to be invisible
117
What does the element.matches() method take as an argument and what does it return?
- takes a selector as its argument and returns a boolean | - ex. element.matches('selector')
118
How can you retrieve the value of an element's attribute?
element.getAttribute('attribute-name-such-as-class-or-src-etc')
119
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?
you would have to put event listeners on every single tab
120
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?
you would have to have functions for every scenario (since there's 3 tabs, you would need 3 functions)
121
What is JSON?
a text-based data format following JavaScript object syntax
122
What are serialization and deserialization?
- serialization: converts object into bytes | - deserialization: converts bytes into object
123
Why are serialization and deserialization useful?
makes it possible to transfer data across different platforms
124
How do you serialize a data structure into a JSON string using JavaScript?
JSON.stringify()
125
How do you deserialize a JSON string into a data structure using JavaScript?
JSON.parse()
126
How do you store data in localStorage?
storage.setItem(keyName, keyValue)
127
How do you retrieve data from localStorage?
storage.getItem(keyName)
128
What data type can localStorage save in the browser?
strings
129
When does the 'beforeunload' event fire on the window object?
before the browser discards the data
130
How can you tell the difference between a method definition and a method call?
- method definition is written inside an object and describes what the method will do with the object - method call carries out the method definition
131
Describe method definition syntax (structure).
``` var newObj = { add: function (x, y) { return x + y; } } ```
132
``` Describe method call syntax (structure). for the following: var newObj = { add: function (x, y) { return x + y; } } ```
newObj.add(3, 2)
133
How is a method different from any other function?
-a method is associated with an object
134
What is the defining characteristic of Object-Oriented Programming?
-software is designed using objects to stand for data (as properties) and behavior (as methods)
135
What are the four "principles" of Object-Oriented Programming?
-abstraction, encapsulation, inheritance, polymorphism
136
What is "abstraction"?
-being able to work with complex things in simple ways, e.g. flipping a light switch, using automatic transmission
137
What does API stand for?
application programming interface
138
What is the purpose of an API?
-allows applications to access and interact with external data
139
What is 'this' in JavaScript?
"this" is an implicit parameter that refers to the object that "this" was located in when it was called
140
What does it mean to say that "this" is an "implicit parameter"?
"this" is an implicit parameter because it's available in a function's code block even though it was never included in the function's parameter list or declared with var
141
When is the value of "this" determined in a function; call time or definition time?
call time!!
142
``` 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); } }; ```
nothing! (not even window) | "this" is present but not yet called
143
``` var character = { firstName: 'Mario', greet: function () { var message = 'It\'s-a-me, ' + this.firstName + '!'; console.log(message); } }; ``` What is the result of the following code snippets, and why? character.greet(); ~~and~~ ``` var hello = character.greet(); hello(); ```
character.greet() will return It's-a-me, Mario! in this code block, "this" is referring to var "character", which has the firstName property of 'Mario'. hello() will return It's-a-me, undefined! here, the greet function is copied from the character object onto "hello", so is now a free-standing function. when hello is called, "this" is referring to window which does not have a firstName property
144
How can you tell what the value of "this" will be for a particular function or method definition?
you can't know the value of "this" until you can see where the function or method is called
145
How can you tell what the value of "this" is for a particular function or method call?
Find where the function is called and look for an object to the left of the dot. if in a general function, the value of "this" is window
146
What kind of inheritance does the JavaScript programming language use?
prototypal chain
147
What is a prototype in JavaScript?
a prototype is a reference to another object that contains common attributes/properties across all instances of the object
148
How is it possible to call methods on strings, arrays, and numbers even though those methods don't actually exist on objects, arrays, and numbers?
prototype object is a built-in property
149
If an object does not have its own property or method by a given key, where does JavaScript look for it?
in the object's prototype (Object.prototype)
150
What does the new operator do?
1. creates a new js object 2. adds a property to the new object (__proto__) that links to the constructor function's prototype object 3. binds the newly created object as the "this" context
151
What property of JavaScript functions can store shared behavior for instances created with new?
prototype
152
What does the instanceof operator do?
- tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object - returns a boolean
153
how do you get a __proto__ property?
it is inherited from the Prototype property of a constructor as a new object from that constructor
154
What is a "callback" function?
-a function passed into another function as an argument or value
155
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?
-setTimeout()
156
How can you set up a function to be called repeatedly without using a loop?
- setInterval() method | - repeatedly calls a function with a fixed time delay between each call
157
What is the default time delay if you omit the delay parameter from setTimeout() or setInterval()?
0 (executed immediately)
158
What do setTimeout() and setInterval() return?
- setTimeout() returns "timeoutID", which is a number that identifies the timer created by the call to setTimeout() - setInterval() returns "intervalID", which is a number that identifies the timer created by the call to setInterval()
159
What is a code block? What are some examples of a code block?
- statements that are grouped together. in js, it's whatever is in the curly brackets. - function() {} - for () {} - if () {}
160
What does block scope mean?
-a variable assigned or declared within the code block can only be seen or accessed within that block
161
What is the scope of a variable declared with const or let?
-block-scoped
162
What is the difference between let and const?
- "let" variables can be reassigned (updated but not re-declared) - "const" variables are read-only references (can neither be updated nor re-declared) - both are block-scoped, neither are global like "var" is
163
Why is it possible to .push() a new value into a const variable that points to an Array?
-only the const variable's reference must remain unchanged. but the Array itself is a separate entity, unbound to const, and can be changed as needed
164
How should you decide on which type of declaration to use?
- if you aren't going to change the variable in the code block, then use "const" - if the variable will be changed, then use "var"
165
What is the syntax for writing a template literal?
`This is a template literal referring to a ${variable}`
166
What is "string interpolation"?
-the ability to substitute part of the string for variables or expressions
167
What is destructuring, conceptually?
-allows you to pull properties from an object/array into a separate variable
168
What is the syntax for Object destructuring?
let { firstName: fname, lastName: lname } = person; | -here, the properties from the variable "person" are pulled as variables "fname" and "lname"
169
What is the syntax for Array destructuring?
let [x, y, z] = getScores(); | -here, the first 3 array elements from getScores() are being assigned to variables x, y, and z
170
How can you tell the difference between destructuring and creating Object/Array literals?
-in destructuring, the stuff to the left of the assignment operator is the array/object, and the stuff on the right of the assignment operator is a variable
171
What is the syntax for defining an arrow function?
- no parameters: need parentheses - 1 parameter: optional parentheses - 2+ parameters: need parentheses
172
When an arrow function's body is left without curly braces, what changes in its functionality?
-only an expression (one line of code is run)... return keyword is not needed
173
How is the value of this determined within an arrow function?
- based on where the arrow function is defined - look outside of the arrow function (the parent function), and if it's another arrow function, then keep looking up and up
174
What is the JavaScript Event Loop?
-the event loop is a model that is responsible for executing the code, collecting and processing events, and executing queued sub-tasks
175
What is different between "blocking" and "non-blocking" with respect to how code is executed?
- "blocking" means that no code is run until the current operation finishes - "non-blocking" means that the program runs asynchronously: it may not necessarily execute line by line. the program calls the function and moves onto the next operation without waiting for the first to return
176
What are the three states a Promise can be in?
- pending: initial state, neither fulfilled nor rejected. - fulfilled: meaning that the operation was completed successfully. - rejected: meaning that the operation failed.
177
How do you handle the fulfillment of a Promise?
then()
178
How do you handle the rejection of a Promise?
catch()
179
What is Array.prototype.filter useful for?
creates a new array with all elements that pass a certain criteria
180
What is Array.prototype.map useful for?
creates a new array populated with the results of calling a provided function on every element in the calling array
181
What is Array.prototype.reduce useful for?
The reduce() method executes a user-supplied “reducer” callback function on each element of the array, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
182
What is the typeof an ES6 class?
function
183
Describe ES6 class syntax.
``` class Person { constructor(name) { this.name = name; } getName() { return this.name; } } ```