Javascript Flashcards
What is the purpose of variables?
to store information to be referenced/accessed later
How do you declare a variable?
use the keyword “var”
- var newVariable
- (also use const/let)
How do you initialize (assign a value to) a variable?
put an equals sign after the variable you want to initialize, and then put the value after the equals sign
e.g. newVariable = ‘new value’
What characters are allowed in variable names?
- variable must begin with: letter, $, or _. after that, numbers can be used as well
- cannot use keywords
What does it mean to say that variable names are “case sensitive”?
capital and lower casing matter
What is the purpose of a string?
stores a sequence of characters (text)
What is the purpose of a number?
gives us a numeric value as a constant to work with
What is the purpose of a boolean?
indicates two possible values (true/false)
What does the = operator mean in JavaScript?
assigns a value to the variable that’s on the left of the operator
How do you update the value of a variable?
varName = ‘new updated value’
What is the difference between null and undefined?
- null is an object with the assigned value of “no value”
- undefined is a type, where the variable is undeclared or undefined (not been given a value)
- in your code, you should not use “undefined”. undefined is generally used for debugging
Why is it a good habit to include “labels” when you log values to the browser console?
so that you know the context for the printed value
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?
combination of 2+ values
What purpose(s) does the + plus operator serve in JavaScript?
adding number values or concatenation
What does the += “plus-equals” operator do?
adds the right-hand value onto the left-hand value and assigns it to the left-hand value
—> (x += 5) is the same as (x = x+5)
What are objects used for?
used to hold a collection of properties and methods
What are object properties?
a name-value pair that tells us more about the object
Describe object literal notation
objectName = { name: value, name2: value2, name3: value3 }
How do you remove a property from an object?
delete objectName.propertyName
What are the two ways to get or update the value of a property?
dot notation, bracket notation
- dot notation is very literal. property identifiers cannot be a variable, or start w a number, or have spaces, etc
- bracket notation has fewer limitations. property identifiers can be variables
What are arrays used for?
arrays store a collection of elements of the same data type
Describe array literal notation.
var newArray = []
How are arrays different from “plain” objects?
- plain objects have properties
- arrays store lists of data of the same type
- arrays have a numeric key [a, b, c] is {0: a, 1: b, 2: c}
What number represents the first index of an array?
0
What is the length property of an array?
tells you how many elements are in the array
How do you calculate the last index of an array?
array.length-1
What is a function in JavaScript?
a block of code that does something or calculates something
Describe the parts of a function definition.
- the function keyword
- an optional name
- zero or more parameters
- a code block
- an optional return statement
function newFunction(parameter1, parameter2) { xyz action return xyz }
Describe the parts of a function call.
functionName(arguments)
When comparing them side-by-side, what are the differences between a function call and a function definition?
- function definition states what action the function will perform w its arguments
- function call invokes the function to perform the action
What is the difference between a parameter and an argument?
- parameter is a placeholder for where arguments will be applied
- argument is the actual value that will be going into the function
Why are function parameters useful?
- states all the information that will be needed to run the function
- allows you to reuse code with different data
What two effects does a return statement have on the behavior of a function?
- causes the function to produce a value
- exits the function
Why do we log things to the console?
console logging helps developers keep track of their code, making sure the outputs are correct
What is a method?
a function stored as a property of an object
How is a method different from any other function?
- a method acts on the data of the object it belongs to
- a function is standalone
How do you remove the last element from an array?
arrayName.pop()
How do you round a number down to the nearest integer?
Math.floor(number)
How do you generate a random number?
Math.random()
- multiply it by a number you want the range of
- the formula==>Math.floor(Math.random() * (end - start) +1) + start
How do you delete an element from an array?
arrayName.splice(start index, # of elements to be deleted, item1 to be added, item2, …)
-only the start index is required as an argument
How do you append an element to an array?
arrayName.push(newElement)
How do you break a string up into an array?
arrayName.split(‘’)
Do string methods change the original string? How would you check if you weren’t sure?
- strings are immutable
- string methods do not change the original string (they create new outputs)
- you can check by console logging the string value
Roughly how many string methods are there according to the MDN Web docs?
30-ish
Is the return value of a function or method useful in every situation?
no, sometimes the function or method is used just to perform an action
Roughly how many array methods are there according to the MDN Web docs?
36
What three-letter acronym should you always include in your Google search about a JavaScript method or CSS property?
MDN
How do you pre-pend an element to an array?
arrayName.unshift()
Give 6 examples of comparison operators.
==, !=, >, =, <=
What data type do comparison expressions evaluate to?
boolean
What is the purpose of an if statement?
sets a condition to help the computer decide which lines of code should be run next
Is ‘else’ required in order to use an if statement?
no
Describe the syntax (structure) of an if statement.
if (condition) {
code to be run if condition is met
}
What are the three logical operators?
and &&
or ||
not !
How do you compare two different expressions in the same condition?
(expression1) &&/|| (expression2)
What is the purpose of a loop?
-run the same block of code a certain amount of time
What is the purpose of a condition expression in a loop?
lets the computer know when to stop the loop
What does “iteration” mean in the context of loops?
represents each instance of the code block in the curly brackets of the loop being run
When does the condition expression of a while loop get evaluated?
after every iteration
When does the initialization expression of a for loop get evaluated?
once, at the beginning
When does the condition expression of a for loop get evaluated?
the condition gets checked at the beginning of every iteration, following initialization
When does the final expression of a for loop get evaluated?
after the code block is run
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 +1 to the variable
How do you iterate through the keys of an object?
“for in” loop
when should you use a for loop vs a while loop vs a do while loop?
- for loop: need to run the code a specific number of times (condition is a counter)
- while loop: need to run the code an unknown number of times (condition is not a counter)
- do while loop: similar to a ‘while loop’ but will always run the statements inside curly brackets at least once, even if the condition is false
Why do we log things to the console?
for debugging purposes so that we know what our output is
What is a “model”?
- a representation of the actual thing
- in the DOM, a model is the data representation of all the objects that make up a web document
Which “document” is being referred to in the phrase Document Object Model?
-web document: the html page
What is the word “object” referring to in the phrase Document Object Model?
-javascript object
What is a DOM Tree?
the data representation of all the objects that make up a web document where there is a parent stem that branches into child branches
Give two examples of document methods that retrieve a single element from the DOM.
- getElementById(‘id-name’)
- querySelector(‘css selector’)
*the best one to use is querySelector
Give one example of a document method that retrieves multiple elements from the DOM at once.
- getElementsByClassName(‘class’)
- getElementsByTagName(‘tagName’)
- querySelectorAll(‘css selector’)
*the best one to use is querySelectorAll
Why might you want to assign the return value of a DOM query to a variable?
so you can re-use that reference in your javascript code without js having to search thru the entire html document
What console method allows you to inspect the properties of a DOM element object?
console.dir(‘element’)
Why would a tag need to be placed at the bottom of the HTML content instead of at the top?
the browser needs to finish loading all the elements in the html page before js can access them
What does document.querySelector() take as its argument and what does it return?
it takes in a css selector and returns the first element in the dom that matches the selector
What does document.querySelectorAll() take as its argument and what does it return?
it takes in a css selector and returns all the elements in the dom that match the selector
What is the purpose of events and event handling?
allows us to execute code only when a certain event is happening
The handler is simply a function which does something (it’s executed) when the event happens. The handler function, by default, when executed is passed the event object (that was created when the event/action you are interested in happened) as an argument.
Are all possible parameters required to use a JavaScript method or function?
-no
-ie. eventTarget.addEventListener takes in up to 4 parameters, but you really only use the first two
eventTarget.addEventListener(type, listener, useCapture, wantsUntrusted)
What method of element objects lets you set up a function to be called when a specific type of event occurs?
.addEventListener(‘click’, handleClick)
‘click’ is the action to listen for
handleClick is your function
What is a callback function?
a function passed into another function as an argument to be executed later
What object is passed into an event listener callback when the event fires?
event object (this will be generated when the event fires. will generate properties such as “event.target”, “event.altKey”, etc)
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 where the element on which the event happened originated from (its reference)
- you can check by console logging “event.target”
- or look it up on MDN
What is the difference between these two snippets of code?
element. addEventListener(‘click’, handleClick)
element. addEventListener(‘click’, handleClick())
- the variable handleClick is held as a callback function (browser will call the function)
- the function handleClick() is called immediately (you are the one calling the function)
What is the difference between event handler and event listener?
- event handler: defines what to do when the function is called (when the event occurs)
- event listener: uses the event handler (callback function) to do something when the event occurs
What is the className property of element objects?
sets/updates/returns the class name of an element
How do you update the CSS class attribute of an element using JavaScript?
$button.className = ‘newClassName’
What is the textContent property of element objects?
represents the text content of the node and also the text content of its descendents
(differs from “innerText” which only represents “human-readable” elments)
How do you update the text within an element using JavaScript?
$button.textContent = ‘new text content’
Is the event parameter of an event listener callback always useful?
no, it’s useful when the handler function needs to know about the event that happened
Why is storing information about a program in variables better than only storing it in the DOM?
if the information is only stored within the DOM, js would have to search other places (like the entire html document) to find it
Does the document.createElement() method insert a new element into the page?
no, it’s stored in a variable and not added to DOM until you use appendChild()
How do you add an element as a child to another element?
appendChild()
What do you pass as the arguments to the element.setAttribute() method?
element. setAttribute(name, value)
- name: a DOMString specifying the name of the attribute
- value: a DOMString containing the attribute’s value
What steps do you need to take in order to insert a new element into the page?
- create the element
- createElement() - give it content (optional)
- createTextNode() - add it to the DOM
- appendChild()
What is the textContent property of an element object for?
return or change the text content of the element
Name two ways to set the class attribute of a DOM element.
- element.className = newClassName
- element.setAttribute(‘class’, ‘value’)
What are two advantages of defining a function to do or create something (like the work of creating a DOM tree)?
- you can reuse the function
- makes the program easier to read because you can organize it into smaller chunks
- need the DOM tree in multiple sections
What property of form a control object gets and sets its value?
value
What property of a form element object contains all of the form’s controls.
elements
What does submitting a form without event.preventDefault() do?
prevents the form from submitting
What does the event.preventDefault() method do?
prevents the default event from happening (checkboxes go unchecked, form submissions do not refresh the page, etc)
What event is fired when a user clicks the “submit” button within a ?
submit
What event is fired as a user changes the value of a form control?
input
What event is fired when a user’s cursor leaves a form control?
blur
What event is fired when a user places their cursor in a form control?
focus
What is the event.target?
where the event occurred (the target object)
Why is it possible to listen for events on one element that actually happen its descendent elements?
event is carried forward to each level of its anscestral chain
What DOM element property tells you what type of element it is?
event.target.tagName
nodeName could also work
What does the element.closest() method take as its argument and what does it return?
targetElement.closest(selectors)
-ex. $button.closest(‘.div-class’)
it returns the DOM element that is closest to the chain that matches the selector
How can you remove an element from the DOM?
element.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?
add it to the closest parent element that contains all the elements (event delegation)
What is the effect of setting an element to display: none?
removes it from the document flow and causes the element and all of its children to be invisible
What does the element.matches() method take as an argument and what does it return?
- takes a selector as its argument and returns a boolean
- ex. element.matches(‘selector’)
How can you retrieve the value of an element’s attribute?
element.getAttribute(‘attribute-name-such-as-class-or-src-etc’)
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 put event listeners on every single 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 have functions for every scenario (since there’s 3 tabs, you would need 3 functions)
What is JSON?
a text-based data format following JavaScript object syntax
What are serialization and deserialization?
- serialization: converts object into bytes
- deserialization: converts bytes into object
Why are serialization and deserialization useful?
makes it possible to transfer data across different platforms
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 localStorage?
storage.setItem(keyName, keyValue)
How do you retrieve data from localStorage?
storage.getItem(keyName)
What data type can localStorage save in the browser?
strings
When does the ‘beforeunload’ event fire on the window object?
before the browser discards the data
How can you tell the difference between a method definition and a method call?
- method definition is written inside an object and describes what the method will do with the object
- method call carries out the method definition
Describe method definition syntax (structure).
var newObj = { add: function (x, y) { return x + y; } }
Describe method call syntax (structure). for the following: var newObj = { add: function (x, y) { return x + y; } }
newObj.add(3, 2)
How is a method different from any other function?
-a method is associated with an object
What is the defining characteristic of Object-Oriented Programming?
-software is designed using objects to stand for data (as properties) and behavior (as methods)
What are the four “principles” of Object-Oriented Programming?
-abstraction, encapsulation, inheritance, polymorphism
What is “abstraction”?
-being able to work with complex things in simple ways, e.g. flipping a light switch, using automatic transmission
What does API stand for?
application programming interface
What is the purpose of an API?
-allows applications to access and interact with external data
What is ‘this’ in JavaScript?
“this” is an implicit parameter that refers to the object that “this” was located in when it was called
What does it mean to say that “this” is an “implicit parameter”?
“this” is an implicit parameter because it’s available in a function’s code block even though it was never included in the function’s parameter list or declared with var
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! (not even window)
“this” is present but not yet called
var character = { firstName: 'Mario', greet: function () { var message = 'It\'s-a-me, ' + this.firstName + '!'; console.log(message); } };
What is the result of the following code snippets, and why?
character.greet();
~~and~~
var hello = character.greet(); hello();
character.greet() will return
It’s-a-me, Mario!
in this code block, “this” is referring to var “character”, which has the firstName property of ‘Mario’.
hello() will return
It’s-a-me, undefined!
here, the greet function is copied from the character object onto “hello”, so is now a free-standing function. when hello is called, “this” is referring to window which does not 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 know the value of “this” until you can see where the function or method is called
How can you tell what the value of “this” is for a particular function or method call?
Find where the function is called and look for an object to the left of the dot.
if in a general function, the value of “this” is window
What kind of inheritance does the JavaScript programming language use?
prototypal chain
What is a prototype in JavaScript?
a prototype is a reference to another object that contains common attributes/properties across all instances of the object
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?
prototype object is a built-in property
If an object does not have its own property or method by a given key, where does JavaScript look for it?
in the object’s prototype (Object.prototype)
What does the new operator do?
- creates a new js object
- adds a property to the new object (__proto__) that links to the constructor function’s prototype object
- binds the newly created object as the “this” context
What property of JavaScript functions can store shared behavior for instances created with new?
prototype
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
- returns a boolean
how do you get a __proto__ property?
it is inherited from the Prototype property of a constructor as a new object from that constructor
What is a “callback” function?
-a function passed into another function as an argument or value
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()
How can you set up a function to be called repeatedly without using a loop?
- setInterval() method
- repeatedly calls a function with a fixed time delay between each call
What is the default time delay if you omit the delay parameter from setTimeout() or setInterval()?
0 (executed immediately)
What do setTimeout() and setInterval() return?
- setTimeout() returns “timeoutID”, which is a number that identifies the timer created by the call to setTimeout()
- setInterval() returns “intervalID”, which is a number that identifies the timer created by the call to setInterval()
What is a code block? What are some examples of a code block?
- statements that are grouped together. in js, it’s whatever is in the curly brackets.
- function() {}
- for () {}
- if () {}
What does block scope mean?
-a variable assigned or declared within the code block can only be seen or accessed within that block
What is the scope of a variable declared with const or let?
-block-scoped
What is the difference between let and const?
- “let” variables can be reassigned (updated but not re-declared)
- “const” variables are read-only references (can neither be updated nor re-declared)
- both are block-scoped, neither are global like “var” is
Why is it possible to .push() a new value into a const variable that points to an Array?
-only the const variable’s reference must remain unchanged. but the Array itself is a separate entity, unbound to const, and can be changed as needed
How should you decide on which type of declaration to use?
- if you aren’t going to change the variable in the code block, then use “const”
- if the variable will be changed, then use “var”
What is the syntax for writing a template literal?
This is a template literal referring to a ${variable}
What is “string interpolation”?
-the ability to substitute part of the string for variables or expressions
What is destructuring, conceptually?
-allows you to pull properties from an object/array into a separate variable
What is the syntax for Object destructuring?
let { firstName: fname, lastName: lname } = person;
-here, the properties from the variable “person” are pulled as variables “fname” and “lname”
What is the syntax for Array destructuring?
let [x, y, z] = getScores();
-here, the first 3 array elements from getScores() are being assigned to variables x, y, and z
How can you tell the difference between destructuring and creating Object/Array literals?
-in destructuring, the stuff to the left of the assignment operator is the array/object, and the stuff on the right of the assignment operator is a variable
What is the syntax for defining an arrow function?
- no parameters: need parentheses
- 1 parameter: optional parentheses
- 2+ parameters: need parentheses
When an arrow function’s body is left without curly braces, what changes in its functionality?
-only an expression (one line of code is run)… return keyword is not needed
How is the value of this determined within an arrow function?
- based on where the arrow function is defined
- look outside of the arrow function (the parent function), and if it’s another arrow function, then keep looking up and up
What is the JavaScript Event Loop?
-the event loop is a model that is responsible for executing the code, collecting and processing events, and executing queued sub-tasks
What is different between “blocking” and “non-blocking” with respect to how code is executed?
- “blocking” means that no code is run until the current operation finishes
- “non-blocking” means that the program runs asynchronously: it may not necessarily execute line by line. the program calls the function and moves onto the next operation without waiting for the first to return
What are the three states a Promise can be in?
- pending: initial state, neither fulfilled nor rejected.
- fulfilled: meaning that the operation was completed successfully.
- rejected: meaning that the operation failed.
How do you handle the fulfillment of a Promise?
then()
How do you handle the rejection of a Promise?
catch()
What is Array.prototype.filter useful for?
creates a new array with all elements that pass a certain criteria
What is Array.prototype.map useful for?
creates a new array populated with the results of calling a provided function on every element in the calling array
What is Array.prototype.reduce useful for?
The reduce() method executes a user-supplied “reducer” callback function on each element of the array, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
What is the typeof an ES6 class?
function
Describe ES6 class syntax.
class Person { constructor(name) { this.name = name; } getName() { return this.name; } }