JavaScript Flashcards
What is the purpose of variables?
Lets us store values and be reusable
How do you declare a variable?
Use keyword var
How do you initialize (assign a value to) a variable?
Use variable name and assignment operator
What characters are allowed in variable names?
Letters, numbers, underscore, dollar sign (cant start with 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
What is the purpose of a string?
Stores text values
What is the purpose of a number?
Stores numeric values
What is the purpose of a boolean?
Stores TRUE or FALSE. Allows for logic and decisions
What does the = operator mean in JavaScript?
The assignment operator
How do you update the value of a variable?
Assign it to a value again, no keyword at the start
What is the difference between null and undefined?
Null is intentionally absent of a value, also an object
Undefined is lack of value since nothing has been done there
Why is it a good habit to include “labels” when you log values to the browser console?
Helps with debugging and context in what we will see in the console
Give 5 examples of JavaScript primitives.
- String
- Boolean
- Number
- Undefined
- Null
What data type is returned by an arithmetic operation?
Number
What is string concatenation?
Using a + to add two or more strings together
What purpose(s) does the + plus operator serve in JavaScript?
It can either add numbers together or concatenate strings into one string
What data type is returned by comparing 2 values ( <, >, ===, etc.)?
Boolean
What does the += “plus-equals” operator do?
It concatenates the strings and returns the expression as a string
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.
A way to create an object
Start with curly braces, then property/method that is paired with a value/function. Use commas to separate those key/value pairs
How do you remove a property from an object?
Use the delete operator
What are the two ways to get or update the value of a property?
Dot notation or bracket notation
What are arrays used for?
Stores list-like info
Describe array literal notation.
Square brackets with values inside being 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?
0
What is the length property of an array?
The number of items in the array
How do you calculate the last index of an array?
array.length - 1
What is a function in JavaScript?
Procedures. It packages code up into a reusable form.
Describe the parts of a function definition.
Function -name of function0 (parameter 1, 2, etc.) {
code block;
optional return value;
}
Describe the parts of a function call.
Name(argument 1, 2,…)
When comparing them side-by-side, what are the differences between a function call and a function definition?
Calls do not have the keyword function
Definitions have a code block
What is the difference between a parameter and an argument?
Parameters are part of the function definition
Arguments are the actual values that get passed in
Why are function parameters useful?
They make the code within the function reusable for multiple variables
What 2 effects does a return statement have on the behavior of a function?
Finds output value of function
Exits the function
Why do we log things to the console?
Helps with debugging and see what are code is doing and working
What is a method?
A function with is a property of an object
How do you remove the last element of an array?
Pop method
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?
pop method
How do you round a number down to the nearest integer?
Math.floor method
How do you generate a random number?
Math.random() generates a pseudo-random number between 0 and 1
How do you delete an element from an array?
Splice method uses 2 arguments (startIndex, numOfItemsToRemove)
Pop method removes from the end
Shift method deletes from the beginning
How do you append an element to an array?
Push method adds to the end
Splice method adds to a specific location
Unshift method adds to the beginning
How do you break a string up into an array?
Split method
Do string methods change the original string? How would you check if you weren’t sure?
No. We can check by using some string methods on a string and 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 an if statement?
Allows our programs to make decisions
Is else required in order to use an if statement?
No
Describe the syntax (structure) of an if statement.
if (expression that evaluates to boolean) { code block } else { code block }
What are the 3 logical operators?
- && (logical and)
- || (logical or)
- ! (logical not)
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
What is the purpose of a loop?
Do a block of code repeated number of times
What is the purpose of a condition expression in a loop?
To check if another loop should be executed
What does iteration mean in the context of loops?
One execution of the code block
When does the condition expression of a while loop get evaluated?
At the beginning of each iteration, including the first
When does the initialization expression of a for loop get evaluated?
At the beginning of the loop (just once)
When does the condition expression of a for loop get evaluated?
At the beginning of each iteration, including the first
When does the final expression of a for loop get evaluated?
At the end of each iteration
Besides a return statement, which exits its entire function block, which keyword exits a loop before its condition expression evaluates to false?
Break
What does the ++ increment operator do?
Increments the value by 1 and returns the current value
How do you iterate through the keys of an object?
Use a for..in loop
What is a ‘model’?
Something that represents something
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, more specifically, the nodes
What is a DOM tree?
The representation of the HTML document using 4 node types (document, element, attribute, text)
Give 2 examples of document methods that retrieve a single element from the DOM.
- document.querySelector()
- document.getElementById()
Give one example of a document method that retrieves multiple elements from the DOM at once.
- document.querySelectorAll()
Why might you assign the return value of a DOM query to a variable?
So we can work with that return value multiple times without having to re-query the tree each time
What console method allows you to inspect the properties of a DOM element object?
console.dir()
Why would a script tag need to be placed at the bottom of the HTML content instead of at the top?
The HTML reads from top to bottom, so the script tag should be at the bottom so the HTML elements are read first
What does document.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 does document.querySelectorAll() take as its argument and what does it return?
IT takes a CSS selector as a string and returns a NodeList, an array-like object of the mating elements of 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
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 the event.target? If you weren’t sure, how would you check? Where could you get more info about it?
event.target is the DOM element that is the start point of the event
To check, we would check the console log
To get more info, check MDN
What is the difference between these two snippets of code?
- element.addEventListener(‘click’, handleClick)
- element.addEventListener(‘click’, handleClick())
The first code snippet will call ‘handleClick(event)’ when the targeted element is clicked
The second code snippet will call the return value of calling the function ‘handleClick()’ which could be another function
What is the className property of element objects?
It lets us retrieve a value or set a value
How do you update the CSS class attribute of an element using JavaScript?
Specify the element to change using ‘querySelector()’ or something similar, then set up the ‘className’ property on the returned element object of that method
What is the textContent property of element objects?
The ‘textContent’ property is a property of a node, and it holds the concatenation of the text content
How do you update the text within an element using JavaScript?
Specify the element with ‘querySelector’ or similar, then set the ‘textContent’ property on the returned element
Is the 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 are not sure what element was interacted with and what element to change
Would the dom-manipulation assignment be simpler or more complicated if we didn’t use a variable to keep track of the number of clicks?
It would be simpler to not have an additional variable to account for, but then we would have to extract the number from the text content of the HTML
Why is storing info about a program in variables better than only storing it in the DOM?
It is 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 form?
‘Submit’ event
What does the event.preventDefault() method do?
It cancels the default behavior
It prevents the event from triggering its default behavior.
What does submitting a form without event.preventDefault() do?
It would reload the page, as long there is no action or method attribute. The form would also be submitted into the server.
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 be going down the wrong path. Somewhere in your many lines of code could be a bug and without checking, you don’t known where to look to fix it
What is an advantage of having your console open when writing a JavaScript program?
You can be checking if your code is running as intended and fix it immediately once an error message shows up
Does the document.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);
What do you pass as the arguments to the element.setAttribute() method?
The name of the attribute and the value
What steps do you need to take in order to insert a new element into the page?
- querySelect for the parent element
- create the element using document.createElement()
- modify the new element by using (element.textContent), (element.setAttribute), etc.
- query the document for the parent element of this new element
- appendChild the new element to the parent element
What is the textContent property of an element object for?
Gets and sets text content of an element and its children via the DOM
Name 2 ways to set the class attribute of a DOM element.
- element.setAttribute() method
- element.className = ‘new-class’
What are 2 advantages of defining a function to do create something (like the work of creating a DOM tree)?
- create consistently structured things with different data repeatedly and concisely
- can tie the function that creates things to event listeners
What is the event.target?
in DOM Event Delegation
The element that was interacted with to trigger the event to fire
Why is it possible to listen for events on one element that actually happen its descendent elements?
The concept of bubbling where clicking on a descendent element is technically clicking on parent elements
What DOM element property tells you what type of element it is?
element.tagName property
What does the element.closest() method take as its argument and what does it return?
It takes a string containing a CSS selector and returns the first element that matches the CSS selector, starting from the element it is called upon itself and moving up its ancestors
How can you remove an element from the DOM?
element.remove()
If you wanted to insert a 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
What is the event.target?
in JavaScript View Swapping
The element that was used in triggering the event
What is the effect of setting an element to display: none?
The element and its child elements are no longer displayed and has no effect on the layout
What does the element.matches() method take as an argument and what does it return?
It takes for an argument a CSS selector as a string and 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?
getAttribute method
At what steps of the solution would it be helpful to log things to the console?
At all steps, but specifically the steps where you are unsure how your objects, variables work
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 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 be queried individually and when a click event happens there would be an ‘if statement’ foe each one. If the view is the one to be made visible, make it visible. If not, make it invisible.
What is JSON?
JavaScript Object Notation. It is away to store data in a string and can easily send info between servers
What are serialization and deserialization?
Serialization- put it in a series format, encode it to be read in serial ( a series of bytes)
Deserialization- take that stream of bytes and reconstruct (parse) it back into an object
Why are serialization and deserialization useful?
We can convert complex data types and break them down into bytes so it can be processed by the network
How do you serialize a data structure into a JSON string using JavaScript?
JSON.stringify method
How do deserialize a JSON string into a data structure using JavaScript?
JSON.parse method
How do you store data in localStorage?
setItem method
How do you retrieve data from localStorage?
localStorage.getItem(‘key’)
What data type can localStorage save in the browser?
Only string types (specifically JSON strings)
When does the ‘beforeunload’ event fire on the window object?
Before the window, document, and its resources are about to be unloaded onto the page
What is a method?
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- function definitions but happen in the definition of an object property
Method calls- object with a function call attached. ex- object.methodCall()
Describe method definition syntax (structure).
var object = { methodName: function (x) { -insert code here- } }
Describe method call syntax (structure).
object.methodName(x);
How is a method different from any other function?
It must be called with an object
What is the defining characteristic of Object-Oriented Programming?
OOP uses objects to store the state of the program and holds the functions that will be used. Objects are the primary interface.
Objects contain both data (as properties) and behaviors (as methods)
What are the 4 principles of Object-Oriented Programming?
- Abstraction
- Encapsulation
- Inheritance
- Polymorphism
What is abstraction?
A simplified interface to something complex
What does API stand for?
Application Programming Interface
What is the purpose of an API?
Allows for a standard way to for 2 or more computer programs to communicate with each other.
What is “this” in JavaScript?
An implicit parameter, determined at the call time, which refers to the object (which is attached to the left of the . )
What does it mean to say that “this” is an ‘implicit parameter’?
It is always an available parameter to the function
When is the value of “this” determined in a function; call time or definition time?
Call time. “this” can refer to new objects depending on when its called
What does “this” refer to in this code snippet?
var character = { firstName: 'Mario', greet: function () { var message = 'It\s-a-me, ' + this.firstName + '!'; console.log(message); } };
We dont know.
Given the above character object, what is the result of the following code snippet? Why?
character.greet();
“It’s-a-me, Mario!”
Given the above character object, what is the result of the following code snippet? Why?
var hello = character.greet; hello();
“It’s-a-me, undefined!”
How can you tell what the value of “this” will be for a particular function or method definition?
We don’t know.
How can you tell what the value of “this” is for a particular function or method call?
Look for an object (something to the left of the . )
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
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?
They are prototyped onto it.
If an object does not have its own property or method by a given key, where does JavaScript look for it?
Looks at the prototype chain.
What does the “new” operator do?
- Creates a blank JavaScript object
- Points object we made to the prototype property of the constructor function
- Takes those values passed in as arguments and binds to those individual objects
- returns the object back, which is how we assign it to a variable
What property of JavaScript functions can store shared behavior for instances created with “new”?
Prototype property
What does the “instanceof” 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
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?
Adding a timeout function
How can you set up a function to be called repeatedly without using a loop?
Add a setInterval function, which runs repeatedly until the interval is cleared
What is the default time delay if you omit the delay parameter from setTimeout() or setInterval() return?
0 milliseconds
What do setTimeout() and setInterval() return?
An interval Id that is tied to the timeout or interval and can be used to clear the interval with
What is AJAX?
It seeks out new info and gets it without reloading the web page
What does the AJAX acronym stand for?
Asynchronous JavaScript and Xml
Which object is built into the browser for making HTTP requests in JavaScript?
Html/Http request object
What event is fired by “XMLHttpRequest” objects when they are finished loading the data from the server?
Load
An “XMLHttpRequest” object has been an addEventListener() method just like the DOM elements. How is it possible that they both share this functionality?
Prototypical inheritance
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 the difference 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.