JavaScript Flashcards
What is the purpose of variables?
To store data that we can go back to later. Permanence of data
How do you declare a variable?
var (variable name) then assignment operator (=) with variable value
How do you initialize (assign a value to) a variable?
var keyword then variable name with the assignment operator (=)
What characters are allowed in variable names?
$, letters, numbers, underscore (variable can’t begin with number
What does it mean to say that variable names are “case sensitive”?
words with lower case and upper case are completely separate things to JavaScript
What is the purpose of a string?
To store characters in a row that JavaScript won’t read as code
What is the purpose of a number?
To store numeric values
What is the purpose of a boolean?
Act as an “on or off” switch (indicating true or false)
What does the = operator mean in JavaScript?
Assignment operator to give something value
How do you update the value of a variable?
You just redeclare that variable as normal, except without the keyword “var”, “let”, or “const”
What is the difference between null and undefined?
undefined is the way JavaScript creates or says something is empty or has no value (empty area which could have been left empty for random reasons)
null is something that we HAVE assign to make something empty or have no value (empty parking lot is on purpose so we can fill it with cars)
Why is it a good habit to include “labels” when you log values to the browser console?
So that we can identify what exactly we are using the console.log method on.
Give five examples of JavaScript primitives.
String, boolean, null, undefined, and numbers
What data type is returned by an arithmetic operation?
number data type
What is string concatenation?
it’s using the plus sign operator to combine two or more strings together
What purpose(s) does the + plus operator serve in JavaScript?
it’s used for string concatenation or adding numbers together
What data type is returned by comparing two values (, ===, etc)?
a boolean
the strict equality operator (three equal signs) checks for same value and type
What does the += “plus-equals” operator do?
it adds the value of the right operand and a variable, then it assigns the result of that expression to the variable.
so a += 3 is the same as “var a = (a’s old value) + 3”
What are objects used for?
objects are used to store a collection of data
What are object properties?
object properties are the keys
Describe object literal notation.
keyword ‘var’ followed by a name then ‘=’ followed by curly brackets ‘{ }’
How do you remove a property from an object?
keyword ‘delete’ followed by object.property
What are the two ways to get or update the value of a property?
bracket notation or dot notation
What are arrays used for?
For representing lists of data
Describe array literal notation.
keyword ‘var’ followed by the variable name then an equal sign with square brackets [ ].
The square brackets are the only part of the array literal notation.
How are arrays different from “plain” objects?
Main thing arrays use numeric indexes (not created by you) while objects have alphanumeric indexes. All arrays come with property name (.length) and it is automatic. You also add stuff into the array differently.
Arrays are more like grocery lists (we care how much is on it) while objects are more like a dictionary.
What number represents the first index of an array?
arrayName[0]
Always starts at index 0
What is the length property of an array?
It stores the total number of items in an array
How do you calculate the last index of an array?
arrayName.length - 1
The length property stores a “true count.” So an array with two item the length is 2, which means we need to subtract 1.
What is a function in JavaScript?
A repeatable block of code
Describe the parts of a function definition.
the var keyboard, function keyword, optional function name, infinite parameters within parenthesis, and then opening curly brace for code block
Describe the parts of a function call.
function name and then the arguments within parenthesis, followed by semi-colon
When comparing them side-by-side, what are the differences between a function call and a function definition?
function definition creates the function and tells it what to do.
function call makes the function do the code.
What is the difference between a parameter and an argument?
A parameter is what a function takes when it is defined. (placeholder values)
An argument is what the function takes when it is called. (real values)
Why are function parameters useful?
They’re placeholders for the future input values. It makes it easier to identify what the function is doing.
What two effects does a return statement have on the behavior of a function?
It specifies a return value for the function and it exits/ends the function.
Why do we log things to the console?
To see how our code is working. It’s a debugging tool to constantly check the output of our code.
What is a method?
A function which is a property of an object
How is a method different from any other function?
A method is predefined? Methods are functions part of an object.
How do you remove the last element from an array?
array.pop()
No value needed in parenthesis
How do you round a number down to the nearest integer?
Math.floor()
It returns the largest integer less than or equal to a given number. So 5.95 is equal to 5, but -3.23 is equal to 3. Math.trunc() does something similar
Math.round is for nearest integer
How do you generate a random number?
Math.random()
Only goes from 0 up to, but not including 1
How do you delete an element from an array?
array.splice()
first parameter is starting point, second parameter is how many deletions, and third parameter is an optional and infinite number of items to add.
How do you append an element to an array?
array.push(‘element’) adds to the end of an array because it’s asking “APPEND” which means add to the end.
while,
array.unshift(‘element’) adds to the front of an array
*infinite # of elements can be taken
How do you break a string up into an array?
string.split() with the parameters being the indicator for what to split the string by. There’s also an optional limit parameter for setting the limit of substrings in the array.
Do string methods change the original string? How would you check if you weren’t sure?
No, Strings are immutable so can’t modify them. To check we would use the console: assign any string to a variable, use the split method with a separator for each character, and then type the string variable again.
Roughly how many string methods are there according to the MDN Web docs?
A lot…40-50
Is the return value of a function or method useful in every situation?
No, sometimes we are just concerned on what the method is doing rather than its return. For example, splice() returns an array of the deleted elements, but we are more concerned with the original array that splice was used on.
Roughly how many array methods are there according to the MDN Web docs?
A lot…40-50
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?
ALWAYS a boolean (true or false)
What is the purpose of an if statement?
do determine if something is true or false, then execute some code based on that value
different behavior based on different data (allow us to make decisions)
Is else required in order to use an if statement?
no it’s not
Describe the syntax (structure) of an if statement.
if keyword, followed by parenthesis enclosing the test condition that compares two operands with a comparison operator then opening/closing curly brace.
What are the three logical operators?
&& (and), || (or), and ! (returns opposite value)
How do you compare two different expressions in the same condition?
Logical && operator and logical || operator (often called ‘pipes’ or vertical bar)
What is the purpose of a loop?
A way to do something more than once without typing it all out ourselves
What is the purpose of a condition expression in a loop?
To set a stopping point for the loop, it’s the brakes
What does “iteration” mean in the context of loops?
A single time that the code block runs
When does the condition expression of a while loop get evaluated?
Before each iteration to decide whether we should stop or not
When does the initialization expression of a for loop get evaluated?
Only at the start, before the first iteration. (it is the first thing that happens before anything else in the loop and it never happens again)
When does the condition expression of a for loop get evaluated?
Happens after the initialization and before each iteration of the loop
When does the final expression of a for loop get evaluated?
After running the code block, but before the condition runs again
Besides a return statement, which exits its entire function block, which keyword exits a loop before its condition expression evaluates to false?
The keyword break
What does the ++ increment operator do?
Increments the operand by 1, BUT it also reassigns the value.
We can use += to increment by more than 1.
i++ vs ++i
Ex: if counter = 1
counter++ + counter++ + ++counter + counter++
1 + 2 + 4 + 4 = 11
2 = 3 = 4 = 5
Answer is 11 for expression. Counter would equal 5.
How do you iterate through the keys of an object?
With a “for in” loop
For var KEYS in OBJECTS; If you need to loop through an object, use for in loop.
Why do we log things to the console?
We log things so that we can be sure that we are targeting/writing code for the right element or to evaluate values
What is a “model”?
A copy of the tree of objects of the HTML page
Which “document” is being referred to in the phrase Document Object Model?
The entire html document
What is the word “object” referring to in the phrase Document Object Model?
Refers to the data type “object” in JavaScript
What is a DOM Tree?
A DOM Tree is a parent element and all of it’s child nodes (a single element and ALL of its content)
DOM definition = A javascript object that is a model of the HTML document (it’s just a copy though)
Give two examples of document methods that retrieve a single element from the DOM.
document. querySelector() and document.getByElementID()
* Should only use document.querySelector() for a single element
Give one example of a document method that retrieves multiple elements from the DOM at once.
document. getElementByClassName()
document. querySelectorAll()
* Should only use document.querySelectorAll() for multiple elements
Why might you want to assign the return value of a DOM query to a variable?
So that you can easily use the location of the element(s) more than once
*It’s common practice to use ‘$’ at the start of a variable name for a DOM method.
It also lets you reuse the same variable name without a $ for something else
What console method allows you to inspect the properties of a DOM element object?
console. dir() - shows everything about the element, but console.log() gives a better visual representation
* Be sure to NOT include a ‘label’ because it doesn’t work with one
Why would a tag need to be placed at the bottom of the HTML content instead of at the top?
To control the order in which things load on the webpage (loads from top to the bottom). We put the script tag at the bottom so it allows the HTML/CSS to load first before we access their elements with JavaScript.
What does document.querySelector() take as its argument and what does it return?
It takes any CSS selector. It returns ONLY the first matching element
- Be sure to have argument wrapped in quotes and as you would write it in CSS
ex: (“.className”)
What does document.querySelectorAll() take as its argument and what does it return?
It takes any CSS selector. It returns ALL matching elements into a nodelist
Why do we log things to the console?
To check what we are working on and to debug scripts
What is the purpose of events and event handling?
Events monitor user inputs which we can use with event handling to execute some code
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?
event.addEventListener()
What is a callback function?
A callback function is a function passed into another function by its definition rather than being called.
Note: function definitions are saved as a type of data by JavaScript
What object is passed into an event listener callback when the event fires?
ex: function mouseClick(event);
$p.addEventListener(‘click’, mouseClick);
We are referring to the event parameter
An object with all the data of the event that just occurred
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 a property of the event object which points to the element WHERE the event occurred. Console.log or google it, more info on mdn.
Note: the “event” we are referring to is NOT the event we pass through
What is the difference between these two snippets of code?
- element.addEventListener(‘click’, handleClick)
- element.addEventListener(‘click’, handleClick())
The first one is using a function definition and the second one is calling the function.
There is NEVER a return for an event handler function. So if we use the second one then the function will be replaced with the function return in this case, nothing or undefined.
What is the className property of element objects?
It gets and sets the class attribute of the specified element
*Good to note that the className property is not the same as the attribute of the html element, it’s just a copy
How do you update the CSS class attribute of an element using JavaScript?
You have to query for the element then use the element.className property.
Ex: element.className = ‘apples’
What is the textContent property of element objects?
The textContent property represents the text content of the specified node and all its descendants (child elements)
How do you update the text within an element using JavaScript?
You have to query for the element then use the textContent property
Ex: document.querySelector(‘div’).textContent = ‘new text content’
Is the event parameter of an event listener callback always useful?
No not always.
*Good to note that you should always include the event parameter so that we can easily identify an event handler function. This tells us we are never calling the function ourself and it tells us that it’s being done in response to something
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 more complicated because we’d have to do more steps in order to reach the same output.
Why is storing information about a program in variables better than only storing it in the DOM?
It makes the information we stored easier to access in the future
What event is fired when a user places their cursor in a form control?
A focus event
What event is fired when a user’s cursor leaves a form control?
A 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?
Prevents the default action of an event. In the case of the form exercise, it stopped the form from refreshing the page with the form values in the URL, which is its default action.
What does submitting a form without event.preventDefault() do?
The page automatically refreshes with the form values in the URL, which is its default action.
What property of a form element object contains all of the form’s controls.
The elements property of the form
What property of a form control object gets and sets its value?
form.element.elementAttribute.value
The ‘value’ property
What is one risk of writing a lot of code without checking to see if it works so far?
You won’t know which part of your code is the problem. If you check the functionality of your code frequently then you can have an easier time in identifying the problem
*You should always do your code one step at a time and then test it
What is an advantage of having your console open when writing a JavaScript program?
You can check to see if the output of your code is what you actually expect it to produce.
Does the document.createElement() method insert a new element into the page?
No, it creates a new element
Note: Always make dom tree that doesn’t change actual HTML and is in a function. That way you can always add it in if you want to
How do you add an element as a child to another element?
You use append.child method which adds the new element as the last child.
You use insertBefore() to add an element where you want or at the front.
Syntax:
- element.appendChild();
- element.insertBefore(new item, target);
What do you pass as the arguments to the element.setAttribute() method?
You pass the attribute name then the attribute value
What steps do you need to take in order to insert a new element into the page?
You need to create a new element with documnent.createElement(), then you CAN set its attributes with element.setAttribute(), then you CAN set its text content with element.textContent = ‘ ‘; and then you need to append it to a parent element with element.appendChild().
*Note you need to querySelector() the parent element before appendChild()
What is the textContent property of an element object for?
It’s used to set or access the text content of an element
Name two ways to set the class attribute of a DOM element.
You can use element.setAtribute() or element.className = ‘ ‘;
What are two advantages of defining a function to create something (like the work of creating a DOM tree)?
The main advantage is that it makes it super easy to test your code.
Ex: What’s the point of getting ALL the pokemon to show if we can’t even get the DOM tree for ONE pokemon
Another benefit is being able to name and reuse a chunk of code
What is the event.target?
It’s the object where the event occurred??
Why is it possible to listen for events on one element that actually happen its descendent elements?
Because of a thing called event flow.
Event bubbling = event starts at most specific node (event.target) and flows out to the least specific node
Event capturing = event starts at least specific node and flows into the most specific one (event.target)
What DOM element property tells you what type of element it is?
event.target.tagName
short answer = .tagName property of an element
What does the element.closest() method take as its argument and what does it return?
It takes a CSS selector string as its argument and it returns itself or the target element’s closest ancestor.
*Note: querySelector() digs into something, while closest() digs out from something
How can you remove an element from the DOM?
Using the element.remove() method.
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?
Wrap whatever elements you want into a parent element, then add the event listener to the parent element.
What is the event.target?
The read-only target property of the Event interface is a reference to the object onto which the event was dispatched. It is different from Event.currentTarget when the event handler is called during the bubbling or capturing phase of the event.
What is the affect of setting an element to display: none?
Turns off the display of an element so that it has no effect on layout (the document is rendered as though the element did not exist). All descendant elements also have their display turned off. To have an element take up the space that it would normally take, but without actually rendering anything, use the visibility property instead.
What does the element.matches() method take as an argument and what does it return?
It checks if the element is the actual selector we are at. The return is a boolean.
How can you retrieve the value of an element’s attribute?
element.getAttribute()
At what steps of the solution would it be helpful to log things to the console?
All steps of the solution
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?
Individually make an event handler for each tab.
Note: The HTML event handler would make itself active and then make everything else off
If you didn’t use a loop to conditionally show or hide the views in the page, how would your JavaScript code be written instead?
A new if statement for each tab and view to cover every case.
JavaScript-and-JSON
What is JSON?
It’s text based data which has similar format to a JavaScript object. It makes it so developers can send an object over a network or store it.
Data interchange format which lets you convert data into a string, but it can go from string to objects
Stands for JavaScript Object Notation
JavaScript-and-JSON
What are serialization and deserialization?
Serialization: The process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file.
Deserialization: The process of fetching a stream of bytes (string) from a network or storage place and converting it back into an object.
*Note: 8 bits in a byte. In reference to binary code (010101 thing)
JavaScript-and-JSON
Why are serialization and deserialization useful?
Serialization is useful because it lets us transfer an object over a network and/or store it in persistent storage (hardrive).
Deserialization is useful for getting this stored object/ sent object and converting it back into an actual object
JavaScript-and-JSON
How do you serialize a data structure into a JSON string using JavaScript?
We turn it into a JSON file by using JSON.stringify() method
JavaScript-and-JSON
How do you deserialize a JSON string into a data structure using JavaScript?
We turn it back into an object by JSON.parse() method.
JavaScript-local-storage
How to you store data in localStorage?
localStorage.setItem(keyName, keyValue)
JavaScript-local-storage
How to you retrieve data from localStorage?
localStorage.getItem(keyName) and it returns null (could be something in the future, but currently nothing) if there’s nothing there
JavaScript-local-storage
What data type can localStorage save in the browser?
ONLY strings
*Useful if formatted as JSON
JavaScript-local-storage
When does the ‘beforeunload’ event fire on the window object?
When the window, document, and its files/resources are ABOUT to be unloaded. So before the user refreshes the page, exits out of it, etc.
Javascript-custom-methods
What is a method?
A function which is a property of an object.
Javascript-custom-methods
How can you tell the difference between a method definition and a method call?
A method definition has the function KEYWORD with parameters being ASSIGNED to a property name and it has a function CODE BLOCK, while a method call has the original OBJECT NAME and an ARGUMENT LIST.
Javascript-custom-methods
Describe method definition syntax (structure).
Method definition looks a lot like property. It has property key name being assigned a function key word with parameters then function code block.
Javascript-custom-methods
Describe method call syntax (structure).
object name DOT method name then arguments
Javascript-custom-methods
How is a method different from any other function?
Not much different except it’s housed in an object
Javascript-custom-methods
What is the defining characteristic of Object-Oriented Programming?
Objects can contain both data (as properties) and behavior (as methods)
Javascript-custom-methods
What are the four “principles” of Object-Oriented Programming?
The four principles are: abstraction, encapsulation, inheritance, and polymorphism.
Javascript-custom-methods
What is “abstraction”?
abstraction is working with (possibly) complex things in a simpler way. *Knowing what something does without knowing how it does it.
Javascript-custom-methods
What does API stand for?
It stands for application programming interface.
Javascript-custom-methods
What is the purpose of an API?
The purpose of an API (roughly means computers interacting/speaking with each other) is to give programmers a way to interact with a system in a simplified, consistent fashion: aka, an abstraction.
“Software abstraction”
Javascript-this
What is this in JavaScript?
It’s an implicit parameter of all JavaScript functions.
*Purpose = variable which holds the value of the current object you’re working with
Javascript-this
What does it mean to say that this is an “implicit parameter”?
It means it doesn’t have to be defined
Javascript-this
When is the value of this determined in a function; call time or definition time?
Call time of the function
Javascript-this
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); } };
‘this’ refers to nothing (meaning doesn’t exist) because the property greet doesn’t have a method call.
you need to invoke the function so, character.greet() to give ‘this’ and a value.
*this is an implicit PARAMETER, which means it has no value until the function is called.
Javascript-this
var character = { firstName: 'Mario', greet: function () { var message = 'It\'s-a-me, ' + this.firstName + '!'; console.log(message); } };
Given the above character object, what is the result of the following code snippet? Why?
character.greet();
The result is: “It’s a me, Mario!”
Because this.firstName refers to the firstName property of character
Javascript-this
var character = { firstName: 'Mario', greet: function () { var message = 'It\'s-a-me, ' + this.firstName + '!'; console.log(message); } };
Given the above character object, what is the result of the following code snippet? Why?
var hello = character.greet; hello()
Result is: “It’s a me, undefined!”
it’s actually ‘window.hello()’, so this refers to window which doesn’t have a property ‘firstName’ so it is undefined .
Character.greet refers to the greet property of character object, BUT hello() has no object.
Javascript-this
How can you tell what the value of this will be for a particular function or method definition?
It can be recognized as the “object to the left of the dot” when the function is called (as a method)
current object??
Javascript-this
How can you tell what the value of this is for a particular function or method call?
Look to the left of the dot. If there is no value to the left of the dot then its default value is the global window object.
Javascript-this
Main benefit of using ‘this’?
It allows us to use objects methods with other objects.
Ex: If we have an object ‘student’ explicitly state a parameter, ‘firstName’, then we can only use that firstName for the student object.
Javascript-prototypes
What kind of inheritance does the JavaScript programming language use?
It uses prototype-based inheritance which means it reuses other objects for behaviors (methods) or data (properties)
Javascript-prototypes
What is a prototype in JavaScript?
A prototype is an object that contains properties and (mostly) methods that can be used by other objects.
Javascript-prototypes
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?
They all have a prototype object which stores a bunch of methods that can be used by strings, arrays, objects, and numbers.
Javascript-prototypes
If an object does not have its own property or method by a given key, where does JavaScript look for it?
In the prototype object it’s attached to
Javascript-constructors
What does the new operator do?
It:
- creates a blank JavaScript object
- adds the property to the new object (__proto__) that links to the constructor function’s prototype object
- Binds the newly created object instance as the ‘this’ context (‘this’ refers to object created)
- Returns ‘this’ if the function doesn’t return an object
Javascript-constructors
What property of JavaScript functions can store shared behavior for instances created with new?
Prototype property
Javascript-constructors
What does the instanceof operator do?
It tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. It returns a boolean.
Javascript-timers
What is a “callback” function?
It’s a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of action/routine.
*Simple: a function being passed as a value for another function
Javascript-timers
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?
Using the global setTimeout() function, which executes a function/piece of code once the timer ends.
*Note: It returns an Interval ID which uniquely identifies the interval. Only a method if called on the window, but nobody does that :/
Javascript-timers
How can you set up a function to be called repeatedly without using a loop?
Using the setInterval() function, which repeatedly calls a function or code snipped, with a fixed time delay between each call.
*Note: It returns an Interval ID which uniquely identifies the interval. Only a method if called on the window, but nobody does that :/
Javascript-timers
What is the default time delay if you omit the delay parameter from setTimeout() or setInterval()?
0 ms, so executes immediately. Technically waits for next event cycle.
Javascript-timers
What do setTimeout() and setInterval() return?
They both return a unique interval ID, which can be used with clearInterval() and/or clearTimeout()
Note: DO NOT USE ID’s for math aka not to be used as actual numbers
http-messages
What is a client?
A client is hardware or software requesting service from a server.
http-messages
What is a server?
A hardware or software that provides a resource/service to other computers
http-messages
Which HTTP method does a browser issue to a web server when you visit a URL?
GET method
http-messages
What three things are on the start-line of an HTTP request message?
- An HTTP method to describe the action to be performed
- The request target, usually a URL
- HTTP version
http-messages
What three things are on the start-line of an HTTP response message?
- Protocol version
- Status code, indicating success or failure of request
- Status text, a brief description of the status code to help a human understand the HTTP message
http-messages
What are HTTP headers?
They’re additional info which the server or client can pass for an HTTP response or request. Grouped as: 1. response/request headers, 2. representation headers, and 3. general headers.
http-messages
Where would you go if you wanted to learn more about a specific HTTP Header?
MDN
http-messages
Is a body required for a valid HTTP request or response message?
No it’s not required for both http request and response. Divided into 3 categories: 1. single-resource bodies on a single line: content-type/content-length, 2. multiple-resource bodies: consisting of different bits of information on the http, 3. For responses: single-resource bodies: consisting of a single file of unknown length, encoded by chunks with transfer-encoding set to chunked
javascript-ajax
What is AJAX?
It’s a programming practice of building complex, dynamic webpages using a technology known as XMLHttpRequest. - From MDN
It’s a web application that can update data without the needing to refresh the page.
*Initially stood for Asynchronous JavaScript And XML
javascript-ajax
What does the AJAX acronym stand for?
*Initially stood for Asynchronous JavaScript And XML
javascript-ajax
Which object is built into the browser for making HTTP requests in JavaScript?
XMLHttpRequest
javascript-ajax
What event is fired by XMLHttpRequest objects when they are finished loading the data from the server?
A load event
javascript-ajax
Bonus Question: An XMLHttpRequest object has an addEventListener() method just like DOM elements. How is it possible that they both share this functionality?
Prototype inheritance, OOP