JavaScript Flashcards
What is the purpose of variables?
to represent/store numbers and other kinds of data
How do you declare a variable?
first you declare a keyword (const, let, var) then you give the variable a name
How do you initialize (assign a value to) a variable?
you assign a variable a value by declaring it, then using an “=” (assignment operator) followed by the value you want to store
What characters are allowed in variable names?
letters
numbers
$
_ (underscore)
What does it mean to say that variable names are “case sensitive”?
if two words are spelled the same, but the cases are different, they will represent different variables
ex var Hello and var hello would be different variables
What is the purpose of a string?
to represent text content (letters and other characters). Must be inside quotations
What is the purpose of a number?
to represent quantities and other calculations involving numeric data
represent numeric data
What is the purpose of a boolean?
to represent “true” or “false” (ie on and off).
What does the = operator mean in JavaScript?
it is the assignment operator
How do you update the value of a variable?
declaring the variable name and using the assignment operator to assign it a new value
ex hello = “hello” reassigns the variable hello to “hello”
What is the difference between null and undefined?
null is an intentional assignment, you must assign a variable to “null” to display no value
undefined is when a variable is assigned no value, i.e. no assignment operator was used.
Why is it a good habit to include “labels” when you log values to the browser console?
to keep track of what variable is being logged and when.
Give five examples of JavaScript primitives.
string number boolean undefined null
What data type is returned by an arithmetic operation?
number
What is string concatenation?
combining strings together to create a new string
What purpose(s) does the + plus operator serve in JavaScript?
serves as addition and/or concatenation
What data type is returned by comparing two values (, ===, etc)?
boolean
What does the += “plus-equals” operator do?
adds the variable (called on the left of the operator) to the value on the right of the operator and then assigns the called variable to the result of that expression.
What are objects used for?
serves as a grouping mechanism for other data types
What are object properties?
variables inside of an object
Describe object literal notation.
assigning an object to a variable name
declaring an object with curly braces
ex
var object = { property: value };
How do you remove a property from an object?
delete operator followed by the object name and property name you want to delete (can use dot or bracket notation).
What are the two ways to get or update the value of a property?
use dot or bracket notation to find the object and property you want and then assign it to a new value.
What are arrays used for?
storing a list of values that are related to each other in an ordered fashion
Describe array literal notation.
brackets assigned to a new variable declaration var arr = [];
How are arrays different from “plain” objects?
arrays are objects, but they have “order”. their index number dictates their property order
What number represents the first index of an array?
0
What is the length property of an array?
tells you how many items are in an array
How do you calculate the last index of an array?
array.length - 1
What is a function in JavaScript?
objects that can carry out tasks that can also be reused.
Describe the parts of a function definition.
“function” keyword
name of function (optional)
function parameter list with optional parameters
opening curly brace
function code block
return statement (optional)
closing curly brace
ex function func(param) {
code
return statement
}
Describe the parts of a function call.
name of function followed by the parameter list (parentheses)
insert parameters inside parenthesis if function needs parameters
When comparing them side-by-side, what are the differences between a function call and a function definition?
function definition has the keyword “function” before the name, and has parameters that act as placeholders within the parenthesis. Then it has the code block that will be executed when the function is called.
function call is just the name followed by parenthesis and arguments.
What is the difference between a parameter and an argument?
a parameter is a placeholder for values to be input into the function
an argument is the actual value that will be placed
Why are function parameters useful?
it allows us to get different results from a function when provided with different values.
What two effects does a return statement have on the behavior of a function?
produces a value for the function
prevents any more code in the functions code block from being run.
Why do we log things to the console?
it allows us to debug our code.
allows us to see the output of our code so we know if something is working as intended.
What is a method?
it is a function that is a property of an object
How is a method different from any other function?
you cannot call the method on its own, it needs to be called by an object
How do you remove the last element from an array?
call the “.pop()” method by the object.
How do you round a number down to the nearest integer?
use the .floor() property on the Math object
ex Math.floor() and pass the number you want rounded down as an argument.
How do you generate a random number?
call the .random() property on the Math object
How do you delete an element from an array?
use the .splice() method on the array.
first argument is the position you want to target
second argument is the number of elements you want to delete
Any argument after is the data you want to insert into that position.
How do you append an element to an array?
.push() method to add to the end of an array
.unshift() method to add to the front of the array
.splice() method to add in the middle of an array.
How do you break a string up into an array?
use the .split() method
first parameter is the “pattern” you want to split the string up by
second parameter is the max number if substrings you want returned
Do string methods change the original string? How would you check if you weren’t sure?
They do not, you need to store the return into a new variable
you can console log the variable that held the original string
Roughly how many string methods are there according to the MDN Web docs?
~50
Is the return value of a function or method useful in every situation?
no
Roughly how many array methods are there according to the MDN Web docs?
~40
What three-letter acronym should you always include in your Google search about a JavaScript method or CSS property?
MDN
Give 6 examples of comparison operators.
== === !== !=== < >
What data type do comparison expressions evaluate to?
booleans (true or false)
What is the purpose of an if statement?
to check if a condition runs true before executing a code
Is else required in order to use an if statement?
no
Describe the syntax (structure) of an if statement.
if keyword condition within parentheses opening curly brace code to be executed closing curly brace
What are the three logical operators?
&& (and)
|| (or)
! (not)
How do you compare two different expressions in the same condition?
you can either use the && or || operators
What is the purpose of a loop?
being able to repeat a block of code under certain conditions
What is the purpose of a condition expression in a loop?
acts as a counter to let the loop know when to stop
What does “iteration” mean in the context of loops?
it is the number of times that a function has repeated
When does the condition expression of a while loop get evaluated?
condition is evaluated BEFORE executing the statement
before iteration
When does the initialization expression of a for loop get evaluated?
initialization expression is evaluated once BEFORE the loop begins
When does the condition expression of a for loop get evaluated?
before the code statement is ran
When does the final expression of a for loop get evaluated?
at the end of the loop iteration and before the condition expression
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?
increase the operand by one
How do you iterate through the keys of an object?
for (let x in object)
x represents the keys in the object
What is a “model”?
the structure of the webpage that it was given.
like a replica of the original thing
Which “document” is being referred to in the phrase Document Object Model?
the html page
What is the word “object” referring to in the phrase Document Object Model?
it refers to the “object’ data type in javascript that makes up the DOM tree
objects are what make up the model
What is a DOM Tree?
a parent element and its “branches” of children and their children
Give two examples of document methods that retrieve a single element from the DOM.
document.querySelector()
getElementById()
Give one example of a document method that retrieves multiple elements from the DOM at once.
document.querySelectorAll()
Why might you want to assign the return value of a DOM query to a variable?
so you can reuse the selector
What console method allows you to inspect the properties of a DOM element object?
console.dir()
Why would a tag need to be placed at the bottom of the HTML content instead of at the top?
so the page can load first before the script is run. if the script is run before the page, it will select nothing.
What does document.querySelector() take as its argument and what does it return?
it takes a selector (in quotes ie a string) and returns the first element that matches the selector
What does document.querySelectorAll() take as its argument and what does it return?
it takes a selector (in quotes) and returns a node list of the document’s elements that match the selector
What is the purpose of events and event handling?
to make the browser respond to user interactions. it makes the the page feel more interactive
events are what the user does and the event handling is what the page does in response to the user events
Are all possible parameters required to use a JavaScript method or function?
no
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 passed into another function as an argument
What object is passed into an event listener callback when the event fires?
the ‘event’ object
it is an object that returns all the relevant information that happened on that event in a object format
What is the event.target? If you weren’t sure, how would you check? Where could you get more information about it?
a property of the Event object. It returns the element where the event occurred.
you can check MDN. search up event.target mdn.
What is the difference between these two snippets of code?
element. addEventListener(‘click’, handleClick)
element. addEventListener(‘click’, handleClick())
no parenthesis is you are calling the method
parenthesis means you are calling the result of the method. It would tell the page that the function will run once the page is loaded, instead of when it is called.
What is the className property of element objects?
it is a property that allows us to get the class names of an element and set the values
How do you update the CSS class attribute of an element using JavaScript?
document.querySelector(‘select element).className = ‘class name’
What is the textContent property of element objects?
property that represents the text content of the selected node and its descendents.
How do you update the text within an element using JavaScript?
document.querySelector(‘select element’).textContent = ‘desired text’
Is the event parameter of an event listener callback always useful?
no
Would this assignment be simpler or more complicated if we didn’t use a variable to keep track of the number of clicks?
more complicated
Why is storing information about a program in variables better than only storing it in the DOM?
it makes it easier to access with JavaScript
What event is fired when a user places their cursor IN a form control?
(ie their cursor is blinking)
‘focus’ is fired when a user clicks on a form
What event is fired when a user’s cursor leaves a form control?
‘blur’ is fired when a user clicks outside an input area
What event is fired as a user changes the value of a form control?
‘input’ is fired when a user starts typing
What event is fired when a user clicks the “submit” button within a form ?
the ‘submit’ event is fired
What does the event.preventDefault() method do?
it prevents the default action of something from occurring.
ie submit wont refresh the page
checking a checkbox won’t fill in a check
What does submitting a form without event.preventDefault() do?
it refreshes the page
What property of a form element object contains all of the form’s controls.
the ‘.element’ property
What property of a form control object gets and sets its value?
the ‘.value’ property
What is one risk of writing a lot of code without checking to see if it works so far?
having to rewrite your entire code if something early on was non-functional
What is an advantage of having your console open when writing a JavaScript program?
being able to see what is happening in real time so you can debug easier.
Does the document.createElement() method insert a new element into the page?
no, it stores it into a variable to be added later with .appendChild()
How do you add an element as a child to another element?
use .appendChild()
attach .appendChild() to the element you want to add to, and insert the actual child into the parenthesis of .appendChild().
What do you pass as the arguments to the element.setAttribute() method?
the name of the attribute you want to set, then the value you want to assign the attribute.
What steps do you need to take in order to insert a new element into the page?
select the parent element you want to target via querySelector() -create the actual element you want to add (ex li, div, ul etc) and store into variable -var newElement = document query + .createNewElement() append some text content to previously mentioned variable (optional) -var newText = document query + .createTextNode(‘string’) newElement.appendChild(newText) append the final variable to the element you want to add to -Parent.appendChild(newElement)
What is the textContent property of an element object for?
it is used for getting all text content within a node and its descendants or to set the value for a node and its descendants
Name two ways to set the class attribute of a DOM element.
.setAttribute(‘class’, ‘classname’)
query.className = ‘classname’
What are two advantages of defining a function to do create something (like the work of creating a DOM tree)?
functions are easier to test, you only need to output one thing in a function vs 20 in a for loop
makes repeating an action easier
What is the event.target?
the element that triggered the event. the most “specific” element that was triggered
Why is it possible to listen for events on one element that actually happen its descendent elements?
because of event flow
default is “bubbling” it selects the most specific (deepest child) element that is within the targeted event
What DOM element property tells you what type of element it is?
event.tagName gets the element in all caps
What does the element.closest() method take as its argument and what does it return?
it takes a string of selectors.
it returns the closest ancestor of the selected element that matched the selector argument that was passed
returns the actual element
How can you remove an element from the DOM?
use .remove() after the selected element you queried for
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 an event listener to the parent element
that parent is then able to listen to any events that happen within it
you can then use methods like tagname or matches() to target more specific events within that parent
What does the element.matches() method take as an argument and what does it return?
takes a string of a css selector
returns a boolean (true or false the element has the selector)
Ex document.querySelector(“li”).matches(“endangered”). If an element of li has a class of “endangered”, the method will return true
How can you retrieve the value of an element’s attribute?
.getAttribute() attached to the targeted element
The argument will be a string value of the name of the attribute value you want
Ie “data-view” will return the value of “data-view”
At what steps of the solution would it be helpful to log things to the console?
after every step
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 add another event listener for each specific tab
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?
several if else statements
if event target matched one condition, you set that one to a certain class name
then you set the other two targets to different class names
create as many if statements as there are targets
What is a breakpoint in responsive Web design?
the point at which a media query is introduced when a style is being deployed.
What is JSON?
JavaScript Object Notation
a string that has a format that resembles javascript objects.’
it contains only properties, no methods
it is a way to serialize data into a string and be able to transfer data more efficiently.
What are serialization and deserialization?
serialization
a way of turning an object into basic memory (eg bytes) so you can transfer the data easier
deserialization
reverse of serialization. Turns a stream of bytes into an object in memory
Why are serialization and deserialization useful?
they allow us convert something and store it in a certain way so we can transfer/store it
deserialization allows us to take stored thing and ‘unpack’ it to its original form
How do you serialize a data structure into a JSON string using JavaScript?
you can use JSON.stringify to turn it into a JSON string
How do you deserialize a JSON string into a data structure using JavaScript?
JSON.parse to unpack the string.
How do you store data in localStorage?
use the .setItem() method and pass in the key and value pair you want to store
How do you retrieve data from localStorage?
you can use the .getItem() method and pass the key you want as a string.
What data type can localStorage save in the browser?
strings
When does the ‘beforeunload’ event fire on the window object?
when the document is about to be ‘unloaded’ meaning before all data is cleared
ie before the data is ‘cleared’
before user leaves the page.
What is a method?
a function that is a property of an object
How can you tell the difference between a method definition and a method call?
definition: the name of the method is a key and the actual function is the value inside an object, and that object is being assigned to a variable
call: the method is attached to an object via dot property