JavaScript Flashcards
What is the purpose of variables?
store information for use later
How do you declare a variable?
var keyword eg var fullName
How do you initialize (assign a value to) a variable?
assignment operator =
What characters are allowed in variable names?
letters, numbers, dollar sign, underscore
What does it mean to say that variable names are “case sensitive”?
upper case and lower case are treated independntly. eg car is not the same as Car
What is the purpose of a string?
represent text
What is the purpose of a number?
represent numeric data type
What is the purpose of a boolean?
represent true or false
What does the = operator mean in JavaScript?
assignment eg var name = “jon”
How do you update the value of a variable?
variable name = (new value)
note that keyword var is not needed
What is the difference between null and undefined?
undefined is a primitive value automatically assigned to variables that have just been declared, or to formal arguments for which there are no actual arguments.
a null value represents a reference that points, generally intentionally, to a nonexistent or invalid object or address.
Why is it a good habit to include “labels” when you log values to the browser console?
clarity in the output - makes it easier to identify.
A console log “label” is simply a short string that describes the variable or value being logged.
Give five examples of JavaScript primitives.
string, number, Boolean, undefined, null – bigint, symbol
What data type is returned by an arithmetic operation?
number
What is string concatenation?
joining together strings
What purpose(s) does the + plus operator serve in JavaScript?
addition and concatenation
What data type is returned by comparing two values (, ===, etc)?
boolean
What does the += “plus-equals” operator do?
addition assignment, adds value and assigns the result to the variable
What are objects used for?
group together a set of properties and methods
What are object properties?
tell us about the object
Describe object literal notation.
similar to css rulesets. var hotel = { name: "quay" }
How do you remove a property from an object?
delete keyword followed by the property name and object name
What are the two ways to get or update the value of a property?
dot notation
object.property
bracket notation
object{‘property’]
What are arrays used for?
storing a list of values that are related to each other
Describe array literal notation.
colors = [‘red’, ‘white’, ‘blue’]
How are arrays different from “plain” objects?
the key for a value in an array is its index number
order matters in an array
arrays have length property
each piece of data is not named
What number represents the first index of an array?
0
What is the length property of an array?
holds the number of items in an array
How do you calculate the last index of an array?
array.length - 1
What is a function in JavaScript?
a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output
Describe the parts of a function definition.
function keyword, name of the function, function parameters, javascript statements in curly braces
Describe the parts of a function call.
name of the function, parenthesis with parameters
When comparing them side-by-side, what are the differences between a function call and a function definition?
function call does not need the function keyword and includes the values for the parameters
What is the difference between a parameter and an argument?
parmeter - placeholder for an argument, value is not known until argument is passed.
argument- actual values passed to the function in place of the parameter
Why are function parameters useful?
they act as placeholders
What two effects does a return statement have on the behavior of a function?
causes the function to produce a value we can use in our program
exits the code block
Why do we log things to the console?
so we can see the output (debugging tool)
What is a method?
a function as a property inside of an object
How is a method different from any other function?
method is associated with an object
How do you remove the last element from an array?
with the pop method
How do you round a number down to the nearest integer?
with the floor method
How do you generate a random number?
random method of the math object
How do you delete an element from an array?
splice method
How do you append an element to an array?
push method
How do you break a string up into an array?
split method
Do string methods change the original string? How would you check if you weren’t sure?
No,
console log the original string
Is the return value of a function or method useful in every situation?
no. eg push will return length of new string
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.
not equal to (!=) strict equal to (===) >< >= <=
What data type do comparison expressions evaluate to?
boolean, true or false
What is the purpose of an if statement?
evaluates a condition, if condition is true then the code block is executed
Is else required in order to use an if statement?
no
Describe the syntax (structure) of an if statement.
keyword, condition, opening curly brace
if (condition >= condition) {
}
What are the three logical operators?
logical and ( && ) logical or ( | | ) logical not ( ! )
How do you compare two different expressions in the same condition?
logical and or logical or operator
eg
((5<2) && (2>=3))
What is the purpose of a loop?
repeat a condition until the loop ends
What is the purpose of a condition expression in a loop?
loop will continue until the condition reaches a specific state or number
What does “iteration” mean in the context of loops?
running the loop once
When does the condition expression of a while loop get evaluated?
before executing the statement
When does the initialization expression of a for loop get evaluated?
once at the start
When does the condition expression of a for loop get evaluated?
before each loop iteration
When does the final expression of a for loop get evaluated?
after each iteration
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?
it increments its operand and returns a value
How do you iterate through the keys of an object?
with a for-in loop
Why do we log things to the console?
so we can see the output
What is a “model”?
a representation of something else
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 in javascript
All of the properties, methods, and events available for manipulating and creating web pages are organized into objects.
What is a DOM Tree?
an element plus all of its children
Give two examples of document methods that retrieve a single element from the DOM.
getElementsById(‘id’)
querySelector(‘css selector’)
Give one example of a document method that retrieves multiple elements from the DOM at once.
getElementsByClassName(‘class’)
Why might you want to assign the return value of a DOM query to a variable?
it saves the browser looking through the DOM tree to find the same elements again
What console method allows you to inspect the properties of a DOM element object?
console.dir()
Why would a tag need to be placed at the bottom of the HTML content instead of at the top?
so that the html can load before the javascript
What does document.querySelector() take as its argument and what does it return?
it takes a css selector and returns the first matching element
What does document.querySelectorAll() take as its argument and what does it return?
it takes a css selector and returns all that match
What is the purpose of events and event handling?
create user interactivity
events - things that happen (could be user interactivity)
Are all possible parameters required to use a JavaScript method or function?
no
What method of element objects lets you set up a function to be called when a specific type of event occurs?
addEventListener
What is a callback function?
a function passed as an argument into another function, 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
What is the event.target? If you weren’t sure, how would you check? Where could you get more information about it?
the selected node, you can console log or console dir
What is the difference between these two snippets of code?
element. addEventListener(‘click’, handleClick)
element. addEventListener(‘click’, handleClick())
the top is a reference to handleClick while the bottom is being executed immediately with no parameters
What is the className property of element objects?
className getsor sets the value of the class attribute
How do you update the CSS class attribute of an element using JavaScript?
element.classname and assignment operator
What is the textContent property of element objects?
represents the text content of the node and its descendents
How do you update the text within an element using JavaScript?
element.textContent = text content
Is the event parameter of an event listener callback always useful?
no
Would this assignment be simpler or more complicated if we didn’t use a variable to keep track of the number of clicks?
more complicated. html only has string data type and would need to be converted
Why is storing information about a program in variables better than only storing it in the DOM?
our program cannot be changed by the user changing text content
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 form
submit event
What does the event.preventDefault() method do?
prevents the events default behavior
What does submitting a form without event.preventDefault() do?
reloads teh page
What property of a form element object contains all of the form’s controls.
elements
What property of a form control object gets and sets its value?
value
What is one risk of writing a lot of code without checking to see if it works so far?
hard to see where it went wrong
What is an advantage of having your console open when writing a JavaScript program?
if something happens the console will throw an error
Does the document.createElement() method insert a new element into the page?
no it creates a new element
How do you add an element as a child to another element?
with the appendchild method
What do you pass as the arguments to the element.setAttribute() method?
class and value of the class
What steps do you need to take in order to insert a new element into the page?
create the new element, add any text content/attributes, then append it to another element
What is the textContent property of an element object for?
represents the text content of the node
Name two ways to set the class attribute of a DOM element.
className property and setAttribute, classlist
What are two advantages of defining a function to create something (like the work of creating a DOM tree)?
it can be reused
it is faster than creating a new one every time
can be updated easily
give name to a process
What is the event.target?
target property of the event. a reference to the object onto which the event was displached
Why is it possible to listen for events on one element that actually happen its descendent elements?
because of 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?
it takes a css selector The closest() method traverses the Element and its parents (heading toward the document root) until it finds a node that matches the provided selector string.
How can you remove an element from the DOM?
using the 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?
add it to an ancestor element
What is the affect of setting an element to display: none?
hides that element from the page
What does the element.matches() method take as an argument and what does it return?
it takes a selector string 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?
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?
new event handler for every single one
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?
an if/else statement for each data view
What is JSON?
JSON is a text-based data format following JavaScript object syntax
useful when you want to transmit data across a network. It needs to be converted to a native JavaScript object when you want to access the data.
What are serialization and deserialization?
Serialization is a process of converting an Object into stream of bytes so that it can be transferred over a network or stored in a persistent storage.
Deserialization is the exact opposite - Fetch a stream of bytes from network or persistence storage and convert it back to the Object with the same state.
Why are serialization and deserialization useful?
you can save the state of an object and recreate it when needed
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?
with the .setitem() method
How do you retrieve data from localStorage?
the getItem() method
What data type can localStorage save in the browser?
strings
When does the ‘beforeunload’ event fire on the window object?
when the window, the document, and its resources are about to be unloaded.
What is a method?
A method is a function which is a property of an object.
How can you tell the difference between a method definition and a method call?
method call: calculator.add()
method definition: add: function (x, y) {
return x + y;
},
Describe method definition syntax (structure).
method name : function keyword, (parameters) { function }
Describe method call syntax (structure).
object.method name (parameters)
How is a method different from any other function?
a method is within an object
What is the defining characteristic of Object-Oriented Programming?
objects can hold data and behavior
What are the four “principles” of Object-Oriented Programming?
abstraction - being able to work with complex things in simple ways
Encapsulation - bundling of data
Inheritance - basing an object or class upon another object or class
Polymorphism - single interface to entities of different types
What is “abstraction”?
abstraction - being able to work with complex things in simple ways
What does API stand for?
application programming interface
What is the purpose of an API?
an application programming interface connects computers or pieces of software to each other
What is this in JavaScript?
this is an implicit parameter of all JavaScript functions. contains a reference to the object
What does it mean to say that this is an “implicit parameter”?
it is 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
given the above character object, what is the result of the following code snippet? Why
It’s-a-me, Mario!
Given the above character object, what is the result of the following code snippet? Why? var hello = character.greet; hello();
its a me undefined
How can you tell what the value of this will be for a particular function or method definition?
cant tell, would be nothing
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
What kind of inheritance does the JavaScript programming language use?
prototypal
What is a prototype in JavaScript?
an object that holds properties or methods
How is it possible to call methods on strings, arrays, and numbers even though those methods don’t actually exist on strings, arrays, and numbers?
the methods are defined on a prototype object and the arrays, strings, and numbers borrow those methods
If an object does not have it’s own property or method by a given key, where does JavaScript look for it?
the prototype
What does the new operator do?
1 Creates a blank, plain JavaScript object.
2 Adds a property to the new object (__proto__) that links to the constructor function’s prototype object
3 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).
4 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
What does the instanceof operator do?
he instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object.
What is a “callback” function?
a function 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, setinterval
How can you set up a function to be called repeatedly without using a loop?
setinterval
What is the default time delay if you omit the delay parameter from setTimeout() or setInterval()?
0
What do setTimeout() and setInterval() return?
an interval ID that can be used by clearinterval and cleartimeout
What is a client?
service requesters
what is a server
providers of a resource or service
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?
method, request target, http version
What three things are on the start-line of an HTTP response message?
protocol version, status code, status text
What are HTTP headers?
line of code. The HTTP headers are used to pass additional information between the clients and the server through the request and response header
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?
no
What is AJAX?
Ajax is 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
What event is fired by XMLHttpRequest objects when they are finished loading the data from the server?
the load event (onload)
An XMLHttpRequest object has an addEventListener() method just like DOM elements. How is it possible that they both share this functionality?
prototypal inheritance
What is a code block? What are some examples of a code block?
code in curly braces, function code block
What does block scope mean?
it refers to the area that a block has jurisdiction
What is the scope of a variable declared with const or let?
block scope
What is the difference between let and const?
let is mutable while const is not
Why is it possible to .push() a new value into a const variable that points to an Array?
The const keyword creates a read-only reference to a value. The readonly reference cannot be reassigned but the value can be change.
How should you decide on which type of declaration to use?
if you need the value to change, use let
if you dont nee it to change , use const
What is the syntax for writing a template literal?
let var = surround string you want in backticks and use ${variable} for the variable you want inserted
What is “string interpolation”?
when JS automatically replaces variables and expressions with their values
What is destructuring, conceptually?
taking something apart
What is the syntax for Object destructuring?
const/let {object property name: variable name} = object
What is the syntax for Array destructuring?
const/let [variable name, variable name, variable name] = array
How can you tell the difference between destructuring and creating Object/Array literals?
which side the array/object name is on
What is the syntax for defining an arrow function?
let add = (x, y) => x + y;
When an arrow function’s body is left without curly braces, what changes in its functionality?
the result is automatically returned
How is the value of this determined within an arrow function?
an arrow function captures the this value of the enclosing context instead of creating its own this context
this is called on definition
What is a CLI?
command line interface
What is a GUI?
graphical user interface, interaction through graphical icons
Give at least one use case for each of the commands listed in this exercise.
man cat ls pwd echo touch mkdir mv rm cp
man - looking up manual cat - combining text files ls - ensuring that you created the files you intended to pwd - you can tell what directory you are currently on echo - touch - create an empty file mkdir - create directories mv - rename directory rm - delete a directory cp - copy a directory
What are the three virtues of a great programmer?
laziness, impatience, and hubris
What is Node.js?
Node.js is a program that allows JavaScript to be run outside of a web browser
What can Node.js be used for?
It is commonly used to build back ends for Web applications, command-line programs, or any kind of automation that developers wish to perform.
What is a REPL?
read eval print loop
a simple interactive computer programming environment that takes single user inputs, executes them, and returns the result to the user; a program written in a REPL environment is executed piecewise
When was Node.js created?
2009
What back end languages have you heard of?
Ruby, PHP, Java, . Net, and Python
What is the process object in a Node.js program?
The process object is a global that provides information about, and control over, the current Node.js process.
How do you access the process object in a Node.js program?
process keyword
What is the data type of process.argv in Node.js?
array of strings
What is a JavaScript module?
a single js file
What values are passed into a Node.js module’s local scope?
exports , require , module , __filename , __dirname
Give two examples of truly global variables in a Node.js program.
console
process
What is the purpose of module.exports in a Node.js module?
allow exporting of a module to be used somewhere else
How do you import functionality into a Node.js module from another Node.js module?
const add = require(‘./add’);
What is the JavaScript Event Loop?
a programming construct or design pattern that waits for and dispatches events or messages in a program.
What is different between “blocking” and “non-blocking” with respect to how code is executed?
Blocking is when the execution of additional JavaScript in the Node.js process must wait until a non-JavaScript operation completes.
all synchronous code is blocking
What module does Node.js include for manipulating the file system?
fs
What method is available in the Node.js fs module for writing data to a file?
fs.writefile
Are file operations using the fs module synchronous or asynchronous?
both
What is NPM?
npm is a package manager for the JavaScript programming language
website, cli, registry
What is a package?
A package is a file or directory that is described by a package.json file
How can you create a package.json with npm?
npm init
What is a dependency and how to you add one to a package?
Packages required by your application in production
npm install name of
What happens when you add a dependency to a package with npm?
npm downloads the dependency
node module gets created
dependency gets put in node-module
library gets added to json
How do you add express to your package dependencies?
npm install express
What Express application method starts the server and binds it to a network PORT?
listen method
How do you mount a middleware with an Express application?
app.use
Which objects does an Express application pass to your middleware to manage the request/response lifecycle of the server?
req, res
What is the appropriate Content-Type header for HTTP messages that contain JSON in their bodies?
application/json
What does the express.json() middleware do and when would you need it?
parses incoming json, need it when receiving json body messages
What is the significance of an HTTP request’s method?
to indicate the desired action to be performed for a given resource
What is PostgreSQL and what are some alternative relational databases?
PostgreSQL is a powerful, free, open source Relational Database Management System (RDBMS). It is often cited as the most advanced open source database of its kind and is well-liked by the developer community for its robust feature set, standards compliance, and reliability.
Other popular relational databases include MySQL (also free), SQL Server by Microsoft, and Oracle by Oracle Corporation.
What are some advantages of learning a relational database?
if you are storing related data, then a relational database is probably a good first choice. A quality of many relational databases is that they support good guarantees about data integrity. Relational databases are arguably the most widely used kind of database.
What is one way to see if PostgreSQL is running?
sudo service postgresql status
What is a database schema?
collection of tables
A schema defines how the data in a relational database should be organized. In relational databases, you typically have to define your schema up front and the database server will make sure that any data being written to the database conforms to that schema.
What is a table?
A table is a list of rows each having the same set of attributes. For example, all students in a “students” table could have “firstName”, “lastName”, and “dateOfBirth” attributes
What is a row?
an entry of data
What is Array.prototype.filter useful for?
anytime you need to filter an array
what is array.map useful for?
mutating an entire array based on a transform function
What is “syntactic sugar”?
In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language “sweeter” for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.
What is the typeof an ES6 class?
function
Describe ES6 class syntax.
class keyword, name of class, class body, prototype methods
what is refactoring?
In computer programming and software design, code refactoring is the process of restructuring existing computer code—changing the factoring—without changing its external behavior.
What must the return value of myFunction be if the following expression is possible?
myFunction()();
function
What does this code do? const wrap = value => () => value;
recursion wrap() returns the function [()=>value]
In JavaScript, when is a function’s scope determined; when it is called or when it is defined?
when it is defined, lexical scope
What allows JavaScript functions to “remember” values from their surroundings?
closures due to lexical scope
What does the acronym LIFO mean?
last in first out
What methods are available on a Stack data structure?
pop push peak print
What must you do to access the value at an arbitrary point in a stack (not just the “top”)?
pop off the values in the stack until you reach the one you want