JavaScript Flashcards
What is the purpose of variables?
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 do youdeclarea variable?
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 do you initialize (assign a value to) a variable?
Use variable name and the assignment operator followed by the value to assign/initialize with (ending with a semicolon) myVar = 23;
What characters are allowed in variable names?
letters, dollar sign ($), underscores (_), and numbers (but cannot start with a number)
What does it mean to say that variable names are “case sensitive”?
Two variable names that are the same letters but with different capitalization will be considered two different variables
What is the purpose of a string?
Stores text values or a string of characters that wouldn’t make sense to JavaScript
What is the purpose of a number?
Stores numeric values not only for calculations but also numeric properties such as screen size. Stores positive and negative integers and decimals
What is the purpose of a boolean?
Like a light switch, it indicates one of two states (true
or false
)
Allows for logic and decisions
What does the=
operator mean in JavaScript?
=
is the assignment operator, meaning it assigns values to variables (or properties, or other stuff)
How do you update the value of a variable?
Assign it a value again, no keyword at the start
What is the difference betweennull
andundefined
?
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
Why is it a good habit to include “labels” when you log values to the browser console?
Without labels, the output can quickly become a very confusing screen of seemingly random values
Give five examples of JavaScript primitives.
string
, number
, boolean
, undefined
, null
, bigint
, symbol
What are the boolean and numeric values of null
and undefined
?
Both are considered false
null
will be 0
in numeric contexts and undefined
will be NaN
What are objects used for?
Objects group together related variables and functions into a single object
What are object properties?
Properties are like variables that are part of an object, they store values like numbers, strings, booleans, arrays, and objects
Describe object literal notation.
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 do you remove a property from an object?
delete myObj.propertyToRemove
or delete myObj['propertyToRemove']
What are the two ways to get or update the value of a property?
Dot notation (myObj.propertyName
) or bracket notation (myObj['propertyName']
)
What are arrays used for?
Stores list-like information, a collection of values that are all related to each other in some way
Describe array literal notation.
Square brackets with values inside delineated by commas
How are arrays different from “plain” objects?
- 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
What number represents the first index of an array?
- 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)
What is thelength
property of an array?
- It contains the number of items in the array, built into arrays
- Number of indexes in there
How do you calculate the last index of an array?
myArray.length - 1
What is a function in JavaScript?
Packaging code up into a reusable and easily referenced form
Describe the parts of a functiondefinition.
function optionalName(param1, param2, ...) { code definition; optional return value }
Describe the parts of a functioncall.
optionalName(arg1, arg2, ...)
When comparing them side-by-side, what are the differences between a functioncalland a functiondefinition?
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.
What is the difference between aparameterand anargument?
Parameters are part of the function definition. Arguments are passed into a function call.
Why are functionparametersuseful?
They make the code within the function reusable for multiple variables so the work can be repeatedly done on similar things
What two effects does areturn
statement have on the behavior of a function?
Stops the execution of the function, meaning no code beyond the first return
is run.
Return replaces a function call with the return value
Why do we log things to the console?
So that we can see what our code is doing throughout the script and check that it is working as intended
What is a method?
A function which is a property of an object
How is a method different from any other function?
They are specific to the object that they belong to and must be called with reference to its object
How do you remove the last element from an array?
myArray.pop()
removes and returns the last element from an array
How do you round a number down to the nearest integer?
Math.floor(myNumber)
How do you generate a random number?
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 do you delete an element from an array?
myArray.splice(startIndex, numOfItemsToRemove)
to remove from specific locationsmyArray.pop()
deletes from the endmyArray.shift()
deletes from the beginning
How do you append an element to an array?
myArray.push()
adds to the end (to append)myArray.splice(startIndex, 0, elementToAdd, nextElementToAdd, ...)
for adding elements at a specific location in the arraymyArray.unshift()
adds to the beginning
How do you break a string up into an array?
myString.split('separator')
breaks up a string along the separator supplied
Do string methods change the original string? How would you check if you weren’t sure?
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
Give 6 examples of comparison operators.
===
, !==
, >
, >=
, `
What data type do comparison expressions evaluate to?
boolean
What is the purpose of anif
statement?
Allows our programs to make decisions, executing some code sometimes and other code (or no code) at other times based on some condition
Iselse
required in order to use anif
statement?
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
Describe the syntax (structure) of anif
statement.
if (expression that evaluates to boolean) {code} else {code}
What are the three logical operators?
&&
, ||
, !
How do you compare two different expressions in the same condition?
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
What is the purpose of a loop?
Do a block of code a repeated number of times
What is the purpose of aconditionexpression in a loop?
To check if another loop should be executed (and to have a way to stop looping at some point)
What does “iteration” mean in the context of loops?
One execution of the code block
_When_does theconditionexpression of awhile
loop get evaluated?
At the beginning of each iteration, including the first
_When_does theinitializationexpression of afor
loop get evaluated?
At the beginning of the loop (just once)
_When_does theconditionexpression of afor
loop get evaluated?
At the beginning of each iteration, including the first
_When_does thefinalexpression of afor
loop get evaluated?
At the end of each iteration
Besides areturn
statement, which exits its entire function block, which keyword exits a loop before itsconditionexpression evaluates tofalse
?
break
What does the++
increment operator do?
Increments the operand that comes before the ++
by 1
and returns the current value
- Both incrementation and substitution
How do you iterate through the keys of an object?
Use a for ... in
loop
- for (var key in object) {code here}
What is a “model”?
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.
Which “document” is being referred to in the phrase Document Object Model?
The web page as a whole
What is the word “object” referring to in the phrase Document Object Model?
The objects of the document, in this case the nodes
JavaScript object data type, storing key-value pairs
What is a DOM Tree?
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)
Give two examples ofdocument
methods that retrieve a single element from the DOM.
.querySelector()
and .getElementById()
Use only .querySelector()
because it’s newer, and reduces number of tools to use
Give one example of adocument
method that retrieves multiple elements from the DOM at once.
.querySelectorAll()
, which is slower than .getElementsByClassName()
and .getElementsByTagName()
Use only .querySelectorAll()
Why might you want to assign the return value of a DOM query to a variable?
So that we can work with the return value multiple times without having to requery the tree each time
Whatconsole
method allows you to inspect the properties of a DOM element object?
console.dir()
Why would ascript
tag need to be placed at the bottom of the HTML content instead of at the top?
The HTML elements must be loaded before JavaScript can access them, so it must be placed after all of the elements
What doesdocument.querySelector()
take as its argument and what does it return?
It takes a CSS selector as a string and returns the first element node that matches the CSS selector
What doesdocument.querySelectorAll()
take as its argument and what does it return?
It also takes a CSS selector as a string and returns a NodeList, an array-like object of the matching elements in the document
What is the purpose of events and event handling?
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
Are all possible parameters required to use a JavaScript method or function?
No, some are optional
What method of element objects lets you set up a function to be called when a specific type of event occurs?
.addEventListener()
What is a callback function?
A function called as an argument by another function
What object is passed into an event listener callback when the event fires?
An event object, based on what was set in the event listener (an object with all the data about the event that just occurred)
What is theevent.target
? If you weren’t sure, how would you check? Where could you get more information about it?
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-onlytarget
property of theEvent
interface is a reference to the object onto which the event was dispatched.
What is the difference between these two snippets of code?
```js element.addEventListener('click', handleClick) ``` ```js element.addEventListener('click', handleClick()) ```
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
What is theclassName
property of element objects?
The className
property holds the class
attribute and allows us to set the class
attribute of the element specified by the element object
How do you update the CSS class attribute of an element using JavaScript?
Specify the element to change using querySelector()
or something similar, and set the className
property on the returned element object of that method
What is thetextContent
property of element objects?
The textContent
is a property of a node, and it holds the concatenation of the text content of the targeted element and its descendants
How do you update the text within an element using JavaScript?
Specify the element with querySelector
or similar, and then set the textContent
property on the returned element
Is theevent
parameter of an event listener callback always useful?
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
Would this assignment be simpler or more complicated if we didn’t use a variable to keep track of the number of clicks?
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
Why is storing information about a program in variables better than only storing it in the DOM?
It’s much easier to modify and use the variable in JavaScript rather than querying for it in the DOM
What event is fired when a user places their cursor in a form control?
'focus'
event
What event is fired when a user’s cursor leaves a form control?
'blur'
event
What event is fired as a user changes the value of a form control?
'input'
event
What event is fired when a user clicks the"submit"
button within a``?
'submit'
event
What does theevent.preventDefault()
method do?
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
What does submitting a form withoutevent.preventDefault()
do?
The form that the submit
is in would get submitted to a server, the regular behavior
What property of a form element object contains all of the form’s controls?
.elements
What property of a form control object gets and sets its value?
.value
What is one risk of writing a lot of code without checking to see if it works so far?
You can end up going down the wrong path, writing code based on false assumptions that would then need to be entirely undone
What is an advantage of having your console open when writing a JavaScript program?
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
Does thedocument.createElement()
method insert a new element into the page?
No, it simply returns a new element node to the JavaScript environment
How do you add an element as a child to another element?
$parentElement.appendChild($childElement);
.append(param1, param2, ...)
can append multiple at once.insertBefore()
as well
What do you pass as the arguments to theelement.setAttribute()
method?
.setAttribute(name-of-attribute, value-of-attribute)
What steps do you need to take in order to insert a new element into the page?
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
What is thetextContent
property of an element object for?
Gets and sets the text content of an element and its children (through the DOM interface objects)
Name two ways to set theclass
attribute of a DOM element.
$element.setAttribute('class', 'new-class')
$element.className = 'new-class'
Also $element.classList = ['new-class']
for a more roundabout way dealing with arrays
What are two advantages of defining a function to do create something (like the work of creating a DOM tree)?
We can create consistently structured things with different data repeatedly and concisely
We can tie the function that creates things to event listeners
What is theevent.target
?
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
Why is it possible to listen for events on one element that actually happen on its descendent elements?
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 )
What DOM element property tells you what type of element it is?
element.tagName
What does theelement.closest()
method take as its argument and what does it return?
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()
How can you remove an element from the DOM?
element.remove()
will remove that element from the DOM, nothing else required
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 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
What is theevent.target
?
The element that was used in triggering the event
What is the affect of setting an element todisplay: none
?
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)
What does theelement.matches()
method take as an argument and what does it return?
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
How can you retrieve the value of an element’s attribute?
element.getAttribute('my-attribute')
At what steps of the solution would it be helpful to log things to the console?
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
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?
Each tab would need an event listener, and any additional tabs would need additional event listeners
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?
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.
What is JSON?
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
What are serialization and deserialization?
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
Why are serialization and deserialization useful?
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
How do you serialize a data structure into a JSON string using JavaScript?
JSON.stringify(myDataStruct)
How do you deserialize a JSON string into a data structure using JavaScript?
JSON.parse(myDataAsString)
How do you store data inlocalStorage
?
localStorage.setItem('key', 'stringValue')
How do you retrieve data fromlocalStorage
?
localStorage.getItem('key')
What data type canlocalStorage
save in the browser?
Only string
types (UTF-16 string format, 2 bytes per character)
When does the'beforeunload'
event fire on thewindow
object?
Just before the window, the document, and its resources are about to be unloaded (discarded)
What is the scope of localStorage
?
Domain level storage
What is amethod?
A function which is a property of an object
How can you tell the difference between a method_definition_and a method_call_?
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()
)
Describe methoddefinitionsyntax (structure).
As a property in an object definition: var myObj = {methodName: function (x, y) {...} }
Describe methodcallsyntax (structure).
myObj.methodName(4, 5);
How is a method different from any other function?
It must be called with an object
What is thedefining characteristicof Object-Oriented Programming?
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
What are the four “principles” of Object-Oriented Programming?
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)
What is “abstraction”?
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)
What does API stand for?
Application Programming Interface
What is the purpose of an API?
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
What isthis
in JavaScript?
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
What does it mean to say thatthis
is an “implicit parameter”?
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
_When_is the value ofthis
determined in a function;call timeordefinition time?
Call time, this
can refer to new objects depending on when it is called
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); } }; ```
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
Given the abovecharacter
object, what is the result of the following code snippet? Why?
js character.greet();
'It's-a-me, Mario!
because this.firstName
will be replaced at call time with character.firstName
which is Mario
Given the above`character`object, what is the result of the following code snippet? Why? ```js var hello = character.greet; hello(); ```
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!
How can you tell what the value ofthis
will be for a particular function or methoddefinition?
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.
How can you tell what the value ofthis
is for a particular function or methodcall?
Look for an object (something to the left of .
)
Otherwise, it will refer to window
What kind of inheritance does the JavaScript programming language use?
Prototypical inheritance
What is a prototype in JavaScript?
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)
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?
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
If an object does not have it’s own property or method by a given key, where does JavaScript look for it?
It looks for the object’s prototype object, and then looks for the property/method by using the key to access the prototype
What does thenew
operator do?
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!**)
What property of JavaScript functions can store shared behavior for instances created withnew
?
prototype
What does theinstanceof
operator do?
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)
What is a “callback” function?
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
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?
Adding a timeout, setTimeout(function, delay)
, will execute the function after the delay in milliseconds has elapsed
How can you set up a function to be called repeatedly without using a loop?
Adding an interval, setInterval(function, delay)
which runs repeatedly every delay
milliseconds until the interval is cleared
What is the default time delay if you omit thedelay
parameter fromsetTimeout()
orsetInterval()
?
0 milliseconds
What dosetTimeout()
andsetInterval()
return?
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.
What is the JavaScript Event Loop?
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.
What is different between “blocking” and “non-blocking” with respect to how code is executed?
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.