JavaScript Flashcards
what is the purpose of a variable?
to store information to be referenced to
How do you declare a variable?
variable keyword and variable name
How do you initialize (assign a value to) a variable?
with an = sign (assignment operator) and a variable value after it
var nameOfVar = value (string, number, boolean data type)
What characters are allowed in variable names?
letters, numbers, dollar sign, or underscore
but a number cannot be the first character
What does it mean to say that variable names are “case sensitive”?
when you call the variable name, you have to call it by its exact value or the computer won’t recognize it
What is the purpose of a string?
to store a collection of characters (could be a letter, number, or a backslash)
What is the purpose of a number?
to store numbers
What is the purpose of a boolean?
to determine which code should run?
to store true/false value
What does the = operator mean in JavaScript?
variable assignment
provide variable value to a variable
How do you update the value of a variable?
call the variable name, assignment operator, and the new variable value
What is the difference between null and undefined?
null is an assigned value– it means there is nothing in the variable
undefined means a variable has been declared but not defined with values yet
as a developer, you never want to assign a variable as undefined
Why is it a good habit to include “labels” when you log values to the browser console?
so you can tell which variables are being logged and in what order– this is especially helpful when you need to debug
Give five examples of JavaScript primitives.
Number, String, Boolean, Null, Undefined
What data type is returned by an arithmetic operation?
number
What purpose(s) does the + plus operator serve in JavaScript?
to concatenate strings or add numbers
What data type is returned by comparing two values (, ===, etc)?
boolean
What does the += “plus-equals” operator do?
adds/concatnates value from the right to the left variable
the current value of that variable, bring in some value, add that on to the current value, and the result of that is the new value
What is string concatenation?
the process of joining multiple strings together
What are objects used for?
used to group together a set of variables and functions to create a model
What are object properties?
a variable– properties tell us about the object
Describe object literal notation.
its an array of key-value pairs with a colon separating the keys and values and a comma after every key-value pair (except for the last)
How do you remove a property from an object?
you use the delete keyword followed by the object name and the property name
What are the two ways to get or update the value of a property?
dot notation or bracket notation
What are object methods?
a function– methods represent tasks that are associated with the object
What are arrays used for?
arrays are used to store a list of values that are related to each other
Describe array literal notation.
values are assigned to the array inside a pair of square brackets and each value is separated by a comma
How are arrays different from “plain” objects?
like objects, arrays hold a key value pairs, but with arrays, the key for each value is its index number
array is a list of items and objects are collections of individual items?
objects are a collection of data with individual name of properties with no set order and arrays are in a set order and are a list of items arrays hold data that are similar
What number represents the first index of an array?
0
What is the length property of an array?
the amount of items in the array
How do you calculate the last index of an array?
array length minus 1
What is a function in JavaScript?
it’s essentially a block of code or statement you write that performs a task or calculates a value and it can be used multiple times
Describe the parts of a function definition.
- function keyword
- function name
- parentheses with parameters inside
- curly braces
- inside curly braces, you have the function code block
Describe the parts of a function call.
- name of the function
- open and close parentheses
- inside the parentheses, you have arguments
When comparing them side-by-side, what are the differences between a function call and a function definition?
a function definition is a lot longer than a function call with all the tasks it needs to perform, however, a function definition alone is not going to perform any action unless the function call calls the function
What is the difference between a parameter and an argument?
parameter is essentially a placeholder for when we call the function and pass in an argument
Why are function parameters useful?
parameters allow us to pass instructions into a function
What two effects does a return statement have on the behavior of a function?
1) causes the function to produce a value we can use
2) prevents any more code in the function code block from being run
Why do we log things to the console?
it informs what the code is doing and alerts you if there’s an issue– so logging things to the console is great for debugging or when you don’t understand code block
to see what the code we’re writing is doing
What is a method?
a method is a function which is a property of an object
a function stored in a property of an object
How is a method different from any other function?
a method is attached to an object
in order to call a method, you have to attach the function name to their object using dot notation, and to call a regular function, you use its name
How do you remove the last element from an array?
pop() method
How do you round a number down to the nearest integer?
floor() method
How do you generate a random number?
Math.random() (from 0 - .9999)
what’s the purpose?
treat it as a percentage, that will get multiplied with your range value
random acts as a decimal
How do you delete an element from an array?
splice() method
arguments: (index, how many elements to remove)
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?
string methods do not change your original string
you can check by logging your value to the console
strings are immutable, you cannot change the original string
Roughly how many string methods are there according to the MDN Web docs?
a lot
Is the return value of a function or method useful in every situation?
no
like the push method, you dont need to know the length of it
Roughly how many array methods are there according to the MDN Web docs?
a lot
What three-letter acronym should you always include in your Google search about a JavaScript method or CSS property?
MDN, official docs, it has all the documents you need
Give 6 examples of comparison operators.
less than, greater than, less than or equal to, greater than or equal to, strictly equal, strictly not equal
What is the purpose of an if statement?
to test conditions, if the condition is true, the subsequent code statement runs
to make decicions
Is else required in order to use an if statement?
no
only use else if you need to
Describe the syntax (structure) of an if statement.
if keyword open and close parenthesis a condition inside the parentheses open and curly braces code to be executed inside the curly braces if condition is true
What are the three logical operators?
logical and operator
logical or operator
logical not operator
How do you compare two different expressions in the same condition?
expression one on one side expression two on the other side and a logical operator in between follow by another pair of parenthesis to wrap the two expressions
by using logical operaters
What data type do comparison expressions evaluate to?
boolean
What is the purpose of a loop?
to repeat similar code a number of times
to repeat code and when to stop repreating code
What is the purpose of a condition expression in a loop?
it lets the loop statement know whether it should be executed
we can think of condition as a break, if its truthy we continue if its falsy we stop
What does “iteration” mean in the context of loops?
repeat?
When does the condition expression of a while loop get evaluated?
first
When does the initialization expression of a for loop get evaluated?
first, before anything, and only once
When does the condition expression of a for loop get evaluated?
second, your condition run betore each iteration
When does the final expression of a for loop get evaluated?
last, after the code block has ran? it is run after the code block
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?
adds one to its operand, increments the variable by one
How do you iterate through the keys of an object?
for in loop
Why do we log things to the console?
to see what the code is doing and to understand what is going on
What is a “model”?
a set of rules that define what type of content each element is allowed to have??
a dom tree?
a representation of something else
Which “document” is being referred to in the phrase Document Object Model?
HTML
What is the word “object” referring to in the phrase Document Object Model?
object is referring to the data type?
What is a DOM Tree?
the dom tree is an element plus all of its containing elements including the child elements, etc
the dom tree is an element holding all other elements
a DOM tree is a tree of elements with the document node at the top (root) which points to the element node which in turn points to its child element nodes (head and body) and so on
from each of those elements, you can navigate the DOM structure and more to different nodes
Give two examples of document methods that retrieve a single element from the DOM.
querySelector() and getElementById()
Give one example of a document method that retrieves multiple elements from the DOM at once.
querySelectorAll()
Why might you want to assign the return value of a DOM query to a variable?
to make it easier to access the value later on
What console method allows you to inspect the properties of a DOM element object?
console.dir() – displays an interactive list of the properties of the specified JavaScript object
the output is presented as a hierarchical listing with disclosure triangles that let you see the contents of child objects
use it when you want to see the data of the dom elements?
Why would a tag need to be placed at the bottom of the HTML content instead of at the top?
it gives the HTML time to load before any of the JS loads
which can prevent errors, and speed up website response time
What does document.querySelector() take as its argument and what does it return?
takes in a selector that describes the element your querying for and returns the HTML element object representing the first element of the specified selectors
What does document.querySelectorAll() take as its argument and what does it return?
takes in a selector and return a node list (an object of a collection of nodes) of the document’s elements that match the specified group of selectors
Why do we log things to the console?
to see what the code is doing
What is the purpose of events and event handling?
events and event handling trigger the code when specific events occur from the user (such as when the user clicks on a button)
without events and event handle, your website is static (not changing)
What do [] square brackets mean in function and method syntax documentation?
it means that that piece is 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 passed into another function as an argument which is then invoked inside the outer function to complete some kind of routine or action
What object is passed into an event listener callback when the event fires?
event object (such as event.target, event.pageX, event.pageY..)
What is the event.target? If you weren’t sure, how would you check? Where could you get more information about it?
you can check on MDN for answer
it returns the node/element that was targeted by the function
get the element that triggered a specific event
the target event property returns the element that triggered the event
the html element that triggered the event
What is the difference between these two snippets of code?
element. addEventListener(‘click’, handleClick)
element. addEventListener(‘click’, handleClick())
the parentheses are omitted where the function is called because they would indicate that the function should run as the page loads (rather than when the event fires)
the first code– handleClick function will run when ‘click’ occur vs the second code–handleClick() will run right away
What is the className property of element objects?
a string value that contain a list of all the classes that applied to that element
How do you update the CSS class attribute of an element using JavaScript?
assignment operator?
you’d need the dom element of that class?
when you are updating a className, you are updating the className attribute?
What is the className property of the element objects?
it gets and sets the value of the class attribute of the specified element
Is the event parameter of an event listener callback always useful?
no, not always usefull
Is the event parameter of an event listener callback always useful?
no, not always useful
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, we’d have to dgo back to the dom to retrieve the counter number and reassignn it to the textContent
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
change event is similar, but stick to input event for now
What event is fired when a user clicks the “submit” button within a ?
submit event
What does the event.preventDefault() method do?
tells the browser that if the event does not get explicitly handled, its default action should not be taken as it normally would be
prevent default method allows you to prevent the default behavior from occurring on an event
ex: when a link (anchor tag) is involved, the behavior default is to navigate to that new URL, but using the method, we’re able to stop the browser from redirecting the page
What does submitting a form without event.preventDefault() do?
the browser would reload the page and submit the data for you and refreshes the page (this is if the form does not have an action attribute (as if action=”insert-link”), it’ll just reload the page)
(with the method, if there’s an action attribute within our form element, it will prevent the browser to send the data over to that link)
What property of a form element object contains all of the form’s controls.
elements property
HTMLFormElement.elements returns an HTMLFormControlsCollection listing all the form controls contained in the form element
you can obtain just the number of form controls using the length property
you can access a particular form control in the returned collection by using either an index or the element’s name or id
(you should just use the name attribute!!)
What property of form a control object gets and sets its value?
value property
What is one risk of writing a lot of code without checking to see if it works so far?
it’ll be hard to find your error(s) throughout the code
What is an advantage of having your console open when writing a JavaScript program?
the console will let you know if there’s an error
What does HTMLFormElement.reset() method do?
this method restores a form element’s default values
it does the same thing as clicking the form’s reset button
Why is it possible to listen for events on one element that actually happen its descendent elements?
this is due to event bubbling– when you hover over a link, for example, javascript can trigger events on the a (anchor tag) element and also any elements the a (anchor tag) element sits inside
What DOM element property tells you what type of element it is?
event.target.tagName or event.target.nodeName
How can you remove an element from the DOM?
using the remove() method
syntax: node.remove()
What does the element.closest() method take as its argument and what does it return?
takes a selector as an argument and returns itself or the cloest matching ancestor
this method traverses the Element and its parents (heading toward the document root) until it finds a node that matches the provided selector string. Will return itself or the matching ancestor
What is the event.target?
it returns the node/element that was targeted by the function
MDN: target property of the Event interface is a reference to the object onto which the event was dispatched
MDN: Event interface represents an event which takes place in the DOM. An event can be triggered by te user’s action e.g. clicking the mouse button
What is the affect of setting an element to display: none?
it turns off the display of an element so that it has no effect on the layout as if the element did not exist
What does the element.matches() method take as an argument and what does it return?
it takes a selector string and returns a boolean
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?
you add the event listener to its parent element
so using event delegation
What is the event.target?
traget property of the event object holds the dom element that the user interact with to trigger that element
element that interacted with (most directly) that trigger that event
it doesn’t matter where you put the event.target you put on, event target will only trigger the element that get interacted with
What is the affect of setting an element to display: none?
display: none, position: absolute and fixed – the document act like these dont exist except for display nis being removed from the documne tlfow
What does the element.matches() method take as an argument and what does it return?
takes a selector and returns a boolean
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?
afterafter 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 add an event listener to every 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?
you would have to write an if statement for each tab
What is JSON?
a text-based data format following on JS object syntax
it’s useful when you want to transmit data across a network
What are serialization and deserialization?
serialization is the process of turning an object in memory into a stream of bytes (turning object, array, value to json string?)
vs
deserialization is the reverse of serialization by turning a stream of bytes into an object in memory (turning json string back into object, value?)
Why are serialization and deserialization useful?
serialization is useful for sending data over the network
deserialization is useful for recreating/retrieving the object in the same state as when you serialized it
people often serialize objects in order to save them to storage, or to send as part of communications. Deserialization is the reverse of that process, taking data structured from some format, and rebuilding it into an object
today, the most popular data format for serializing data is JSON.
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 do you store data in the localStorage property?
setItem() method
localStorage.setItem()
How do you retrieve data from the localStorage property?
getItem() method
localStore.getItem()
What data type can localStorage save in the browser?
string
When does the ‘beforeunload’ event fire on the window object?
when the window, the document and its resources are about to be unloaded
refreshing your page, closing browser, navigating to another link would trigger beforeunload
What is a method?
a method is a function which is a property of an object
2 kinds of methods:
1) Instance Methods – built in tasks performed by an object instance
2) Static Methods – tasks that are called directly on an object constructor
How can you tell the difference between a method definition and a method call?
a method definition is an function that is being defined in an object with the function code block vs a method call is an object function that is being called with ()
Describe method definition syntax (structure).
property name describing the following function follow by a colon then the function keyword with open and close parentheses (), with optional parameters inside of the (), follow by an open curly brace, and the function code block, then a closing curly brace
Describe method call syntax (structure).
object name follow by the object’s property and a ()
How is a method different from any other function?
a method has to be declared inside of an object
methods are just normal function
a function in a property
method can referenced the object they’re inside of
What is the defining characteristic of Object-Oriented Programming?
OOP can contain both data (properties) and behaviors (methods)
instead of having to pass each data that you would need as arguments, you would have all of this data inside the function and the function can access all of these data (where you behaviors is stored)
What are the four “principles” of Object-Oriented Programming?
abstraction, encapsulation, inheritance, polymorphism
What is “abstraction”?
according to MDN, abstraction is a way to reduce complexity and allow efficient design and implementation in complex software systems
it hides the technical complexity of systems behind simpler APIs
What does API stand for?
Application Programming Interface
allows programs to interact with each other in an abstract way
What is the purpose of an API?
give programmers a way to interact with a system in a simplified, consistent fashion (which is abstraction)
What is “this” in JavaScript?
“this” is an implicit parameter of all JS functions
by default, “this” will be the global “window” object
syntax: the value of “this” can be recognized as “the object to the left of the dot” when the function is called (as a method)
the value of “this” is determined at call time
What does it mean to say that this is an “implicit parameter”?
it means that it is available in a function’s code block even though it was never included in the function’s parameter list or declared as a variable
implicit parameter is a value within each function without having to declare it yourself
When is the value of this determined in a function; call time or definition time?
the value of “this” is determined at call time
How can you tell what the value of this will be for a particular function or method definition?
you can’t
How can you tell what the value of this is for a particular function or method call?
the value of this can be recognized as “the object to the left of the dot” when the function is called (as a method)
What kind of inheritance does the JavaScript programming language use?
prototype-based inheritance
What is a prototype in JavaScript?
a JS prototype is simply an object that contains properties and methods that can be used by other objects
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?
we use the method that are defined on the prototype object
it’s the __proto__ property attached to each object (object, array..) and the proto property has a list of methods
if it doesn’t find the method, it returns an error
If an object does not have it’s own property or method by a given key, where does JavaScript look for it?
look at its prototype
What does the new operator do?
let us create a version/ an instance to use of one type of thing
IMPT: your constuctor function should never return a statement, “This” is already returned implicitly because we used a new operator
What property of JavaScript functions can store shared behavior for instances created with new?
prototype property
prototype property should only be used on constructor functions
What does the instanceof operator do?
it will check if the object on the right of the operator is a prototype of the object on the left of the operator
What is a “callback” function?
a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action
ex:
function greeting(name) {
alert(‘Hello ‘ + name);
}
function processUserInput(callback) { var name = prompt('Please enter your name.'); callback(name); }
processUserInput(greeting);
this is an example of a synchronous callback, as it is executed immediately.
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?
by using setTimeOut function
it allows us to call another function and a time determined by us
How can you set up a function to be called repeatedly without using a loop?
setInternal function
What is the default time delay if you omit the delay parameter from setTimeout() or setInterval()?
0s
What do setTimeout() and setInterval() return?
a timer id
they both pull from the same timer id (so they wont overlap?)
What is AJAX?
(USE DEFINITION IN BOOK)
a technique for loading data into part of a page without having to refresh the entire page
allows you to request data from a server and load it without having to refresh the entire page
the data is often sent in JSON format
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 event?
An XMLHttpRequest object has an addEventListener() method just like DOM elements. How is it possible that they both share this functionality?
because XMLHttpRequest is an object, therefore, it has access to the AddEventListener() method?
due to inheritance, they both have EventTarget.prototype in their prototype chains
Why do we use the XMLHttpRequest object?
we use this it to issue http requests in order to exchange data between the web site and a server
What is Array.prototype.filter useful for?
useful for filtering out the values you don’t want in an array and store it in a new array
What is Array.prototype.map useful for?
useful for looping over every element in an array and returning a new array
What is Array.prototype.reduce useful for?
when you want an accumulation of/combined an array resulting in a single output value (and the return doesn’t have to be an array)
to take a list of things and collapse it down
What is “syntactic sugar”?
syntax that is designed to make things easier to read and write
What is the typeof an ES6 class?
function
Describe ES6 class syntax.
- class keyword
- name of class in with the first letter being capitalized
- a pair of curly braces (this is call the body of the class)
- within it, a constructor function
- some methods definition
(constructor function is where you can initialize the properties of an instance)
What is “refactoring”?
the process of restructuring computer code without changing or adding to its external behavior and functionality
key thing: behavior of the system doesn’t change
In JavaScript, when is a function’s scope determined; when it is called or when it is defined?
when it is defined
What allows JavaScript functions to “remember” values from their surroundings?
closures
✧ what is a closure?
combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment)
closure gives you access to an outer function’s scope from an inner function
in js, closures are created every time a function is created, at function creation time