JavaScript Flashcards
What is the purpose of variables?
data storage
How do you declare a variable?
var name;
How do you initialize (assign a value to) a variable?
variable name = variable value;
What characters are allowed in variable names?
letters, numbers, $, underscore
What does it mean to say that variable names are “case sensitive”?
two variables can share the same name but have different capitalization, making them different variables (don’t do this; it’s bad practice)
What is the purpose of a string?
storage of text data
What is the purpose of a number?
storage of numeric data types
What is the purpose of a boolean?
to make decisions
What does the = operator mean in JavaScript?
assignment operator
How do you update the value of a variable?
variable name = new value;
What is the difference between null and undefined?
- null: intentional absence created by a human
- undefined: lack of value recognized by JavaScript
Why is it a good habit to include “labels” when you log values to the browser console?
for clarity and to describe the variable or value being logged
Give five examples of JavaScript primitives
string, number, boolean, null, undefined
What data type is returned by an arithmetic operation?
numeric
What is string concatenation?
adding two or more strings together to create a new string
What purpose(s) does the + plus operator serve in JavaScript?
arithmetic, concatenation
What data type is returned by comparing two values (< , > , ===, etc.)?
boolean
What does the += “plus-equals” operator do?
adds another value to variable and the result of that expression gets assigned to the variable
What are objects used for?
to group together a set of variables and functions
What are object properties?
variables
Describe object literal notation
var object = {
};
How do you remove a property from an object?
by using 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?
store lists of data
Describe array literal notation
var name = [ ];
How are arrays different from “plain” objects?
only uses numeric index, contains a length property that is constantly updated, multiple methods to interact with arrays
What number represents the first index of an array?
0 (zero)
What is the length property of an array?
stores (true) count of number of items are in array
How do you calculate the last index of an array?
subtract 1 from the variable
What is a function in JavaScript?
a set of code block for performing a task that is reusable
Describe the parts of a function definition
function keyword, name, parameters list, {code block};
Describe the parts of a function call
function name(arguments);
there can be 0 to many arguments
When comparing them side-by-side, what are the differences between a function call and a function definition?
function call: there is a function name followed by (); - executes code
function definition: there is a function keyword and a code block
- code does not run
- gives function a name
What is the difference between a parameter and an argument?
parameter: placeholder for argument value
- value is unknown until function gets called and argument(s) is passed
argument: a known value that gets passed when a function is called
Why are function parameters useful?
- serves as a placeholder for arguments
- allows for varying results based on arguments that will get passed later on
- reusable behavior
What two effects does a return statement have on the behavior of a function?
- causes function to produce a value that can be used in programming
- prevents any more code in function code block from being run
Why do we log things to the console?
debugging
What is a method?
- a function which is a property of an object
- in JavaScript functions themselves are objects, so, in that context, a method is actually an object reference to a function
How is a method different from any other function?
methods are part of an object
How do you remove the last element from an array?
pop()
How do you round a number down to the nearest integer?
Math.floor()
How do you generate a random number?
Math.random()
How do you delete an element from an array?
splice()
How do you append an element to an array?
push()
How do you break a string up into an array?
split()
Do string methods change the original string? How would you check if you weren’t sure?
strings are immutable; call a method to check the values
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, it varies by situation
Roughly how many array methods are there according to the MDN Web docs?
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
== equal to === strict equal to != not equal to > >=
What data type do comparison expressions evaluate to?
boolean
What is the purpose of an if statement?
allows for decision-making and different pathways for code
Is else required in order to use an if statement?
no
Describe the syntax (structure) of an if statement
if (condition) {
statement
};
What are the three logical operators?
&& logical and
|| logical or
! logical not
How do you compare two different expressions in the same condition?
(expression) && (expression)
expression) || (expression
What is the purpose of a loop?
to check a condition repeatedly until it returns false
What is the purpose of a condition expression in a loop?
tells the loop when to stop
What does “iteration” mean in the context of loops?
how ever many times the code block runs
When does the condition expression of a while loop get evaluated?
before each iteration
When does the initialization expression for a for loop get evaluated?
once, before the loop begins
When does the condition expression for a for loop get evaluated?
after initialization and before each loop iteration
When does the final expression of a for loop get evaluated?
after code block runs and 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?
break keyword
What does the ++ increment operator do?
adds one, returning a value that substitutes the current value
How do you iterate through the keys of an object?
using for…in loop
Why do we log things to the console?
to look at the outputs we’re working with and to also debug when a problem occurs
What is a “model?”
a replica of something
Which “document” is being referred to in the phrase Document Object Model?
HTML document
What is the word “object” referring to in the phrase Document Object Model?
data type object
What is a DOM tree?
a representation of the objects in HTML, including the parent element, child element, nodes
Give two examples of document methods that retrieve a single element from the DOM
.querySelector(‘css selector’)
.getElementById(‘id’)
Give one example of a document method that retrieves multiple elements from the DOM at once
.querySelectorAll(‘css selector’)
Why might you want to assign the return value of a DOM query to a variable?
to access it again later (also for efficiency)
What console method allows you to inspect the properties of a DOM element object?
console.dir
dir = directory
Why would a < script > tag need to be placed at the bottom of the HTML content instead of at the top?
HTML document loads from top to bottom so the browser needs to parse all elements before JavaScript code can access it
What does document.querySelector() take as its argument and what does it return?
CSS selector; the first matching element
What does document.querySelectorAll() take as its argument and what does it return?
CSS selector; all matching elements (nodelist)
What is the purpose of events and event handling?
creates interactivity with the user; code responds to events triggered by the user
Are all possible parameters required to use a JavaScript method or function?
no because there could be a function with no parameters
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, which is then invoked inside outer function to complete an action
What object is passed into an event listener callback when the event fires?
an object with all 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 information about it?
property of the event object and the element where the event occurred; check MDN
What is the difference between these two snippets of code?
element. addEventListener(‘click’, handleClick)
element. addEventListener(‘click’, handleClick())
- the first snippet is a function definition
- the second snippet is a function call
- the event handler will be undefined because the function call gets replaced with a return
- there is never a return for an event handler function
What is the className property of element objects?
property that sets the value of the class attribute of the specified element
How do you update the CSS class attribute of an element using JavaScript?
query for the element, get new value, re-assign value to element using .className
What is the textContent property of element objects?
text content of specified node and its descendants
How do you update the text within an element using JavaScript?
query for the element, get new value, re-assign value to element using .textContent
Is the event parameter of an event listener callback always useful?
no; only needed when you need to know where the event occurred
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 because you would need to retrieve text, convert it to a number, then return it
- variables are easier to work with and easy to identify
Why is storing information about a program in variables better than only storing it in the DOM?
- more efficient and is easily accessible by JavaScript
- data should be stored in JavaScript to keep track of values
What event is fired when a user places their cursor in a form control?
focus
What event is fired when a user’s cursor leaves a form control?
blur
What event is fired as a user changes the value of a form control?
input
What event is fired when a user clicks the “submit” button within a ?
submit
What does the event.preventDefault() method do?
prevents default behavior from happening
e.g., browser automatically reloading page with form values in URL
What does submitting a form without event.preventDefault() do?
it reloads the page with form values
What property of a form element object contains all of the form’s controls?
.elements
elements property
What property of a form control object gets and sets its value?
.value
value property
What is one risk of writing a lot of code without checking to see if it works so far?
not knowing where a problem occurred and its effect on other lines of code
What is an advantage of having your console open when writing a JavaScript program?
see code in action, be able to spot problems and fix them as needed
Does the document.createElement() method insert a new element into the page?
it creates an element node, but it’s on the page or visible yet
How do you add an element as a child to another element?
.appendChild
append = to add to the end
What do you pass as the arguments to the element.setAttribute() method?
(name, value)
What steps do you need to take in order to insert a new element into the page?
- create element
- give it content
- query DOM for target parent
- add to DOM by appending child to parent
What is the textContent property of an element object for?
- text content of the node and its descendants
- it can be used to retrieve and set text content of an element
Name two ways to set the class attribute of a DOM element.
.setAttribute
.querySelector for the element then assign string to class name property
What are two advantages of defining a function to do create something (like the work of creating a DOM tree)?
- can test the function to see what it returns when an argument is passed
- can reuse the code later
What is the event.target?
it returns the element that was triggered by an event
Why is it possible to listen for events on one element that actually happen on its descendent elements?
event bubbling
What DOM element property tells you what type of element it is?
.tagName
What does the element.closest() method take as its argument and what does it return?
string selector; closest ancestor element
How can you remove an element from the DOM?
.remove()
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 it on a parent element then add event listener on that parent element
What is the affect of setting an element to display: none?
it will disappear and be removed from document flow
What does the element.matches() method take as an argument and what does it return?
selector string; boolean
How can you retrieve the value of an element’s attribute?
.getAttribute()
At what steps of the solution would it be helpful to log things to the console?
all steps
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?
- create custom individual event handler for each tab
- use .querySelector() instead of .querySelectorAll()
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?
add a new if statement for each tab
What is JSON?
- JavaScript Object Notation
- text-based data format that exists as a string, following JavaScript object syntax
What are serialization and deserialization?
- serialization: converting object to a string/series of bytes
- deserialization: converting string/stream of bytes to a native object
Why are serialization and deserialization useful?
useful for when you want to transmit data across a network or need data to be stored on a disk
How do you serialize a data structure into a JSON string using JavaScript?
JSON.stringify()
How do you deserialize a JSON string into a data structure using JavaScript?
JSON.parse()
How to you store data in localStorage?
.setItem(key, value)
How to you retrieve data from localStorage?
storage.getItem(keyName)
if empty, it will return null
What data type can localStorage save in the browser?
strings
When does the ‘beforeunload’ event fire on the window object?
when the window is about to close or refresh
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 definition: contains a function keyword, code block, and is being assigned to a property
- method call: only contains name of object followed by the method ()
Describe method definition syntax (structure).
property name : function (parameters) { //code block; };
Describe method call syntax (structure).
object.method();
How is a method different from any other function?
it’s a property of an object
What is the defining characteristic of Object-Oriented Programming?
objects can contain both data (as properties) and behavior (as methods)
What are the four “principles” of Object-Oriented Programming?
abstraction, encapsulation, inheritance, polymorphism
What is “abstraction”?
simplifying complex concepts
What does API stand for?
Application Programming Interface
What is the purpose of an API?
software abstraction; simplifying complex behavior so people can use it without having to fully understand how something actually works
What is this in JavaScript?
an implicit parameter of all JavaScript functions
What does it mean to say that this is an “implicit parameter”?
always present in function’s code block even though it was never included in the parameter list or declared with a variable
When is the value of this determined in a function; call time or definition time?
call time
What does this refer to in the following code snippet?
var character = { firstName: 'Mario', greet: function () { var message = 'It\'s-a-me, ' + this.firstName + '!'; console.log(message); } };
- nothing; there is no “this” yet
- method must be called first
Given the character object below, what is the result of the following code snippet?
character.greet();
Why?
var character = { firstName: 'Mario', greet: function () { var message = 'It\'s-a-me, ' + this.firstName + '!'; console.log(message); } };
It’s-a-me, Mario!
- the greet method is being called on the character object
Given the character object below, what is the result of the following code snippet?
var hello = character.greet; hello();
Why?
var character = { firstName: 'Mario', greet: function () { var message = 'It\'s-a-me, ' + this.firstName + '!'; console.log(message); } };
It’s-a-me, undefined!
- “this” is the window which doesn’t have a firstName property
How can you tell what the value of this will be for a particular function or method definition?
you can’t bc it doesn’t have a value until it is called
How can you tell what the value of this is for a particular function or method call?
the object to the left of the dot when the function is called
What kind of inheritance does the JavaScript programming language use?
prototypal inheritance
What is a prototype in JavaScript?
a model of an object that other objects can use to build upon
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?
by using the prototype object, which contains properties and methods that can be used by other objects
If an object does not have its own property or method by a given key, where does JavaScript look for it?
it borrows from the prototype object
What does the new operator do?
- creates a blank, plain JavaScript object
- adds a 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 (i.e. all references to this in the constructor function now refer to the object created in the first step)
- returns this if the function doesn’t return an object
What property of JavaScript functions can store shared behavior for instances created with new?
prototype property
What does the instanceof operator do?
tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object (return value is a boolean)
What is a “callback” function?
a function that gets passed into another function as an argument
Besides adding an event listener callback function to an element or the document, what is one way to delay the execution of a JavaScript function until some point in the future?
setTimeout() function
How can you set up a function to be called repeatedly without using a loop?
setInterval() function
What is the default time delay if you omit the delay parameter from setTimeout() or setInterval()?
zero
What do setTimeout() and setInterval() return?
a numeric, non-zero value (ID) which identifies the timer created
What is a client?
a piece of software that accesses a service made available by a server as part of the client-server model
What is a server?
a computer hardware or software that provides functionality for other programs or devices known as clients
(wait for a request from client and provide what was requested)
Which HTTP method does a browser issue to a web server when you visit a URL?
GET
What three things are on the start-line of an HTTP request message?
- an HTTP method that describes the action to be performed
- the request target, usually a URL or absolute path of the protocol, port, and domain
- the HTTP version, which defines the structure of the remaining message, acting as an indicator of the expected version to use for the response
What three things are on the start-line of an HTTP response message?
- the protocol version, usually HTTP/1.1
- a status code (success or failure) of the request
- a status text providing description of the status code to help person understand the HTTP message
What are HTTP headers?
- an HTTP header consists of its case-insensitive name followed by a colon (:), then by its value
HTTP headers…
- let the client and the server pass additional information with an HTTP request or response
- allow you to provide additional metadata about the request or response
Where would you go if you wanted to learn more about a specific HTTP Header?
MDN
Is a body required for a valid HTTP request or response message?
- a body is optional
- applicable in certain cases like 201, which indicates that data was successfully created
What is AJAX?
a technique for loading data into part of a page without having to refresh the entire 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?
XMLHttpRequest object
What event is fired by XMLHttpRequest objects when they are finished loading the data from the server?
load
An XMLHttpRequest object has an addEventListener() method just like DOM elements. How is it possible that they both share this functionality?
prototypal inheritance