JavaScript Flashcards
What is the purpose of variables?
a container used to store data so that you can use it later
How do you declare a variable?
using let, const, or var keyword and then giving it a name in camelCase
How do you initialize (assign a value to) a variable?
using = e.g.(var x = 2)
What characters are allowed in variable names?
letters, numbers, $ sign, and underscore
What does it mean to say that variable names are “case sensitive”?
two variables can have the same name but different values if their first letter is capitalized and uncapitalized
What is the purpose of a string?
used to store and represent text information
What is the purpose of a number?
used to store and represent numerical values and do math
What is the purpose of a boolean?
used for conditional statements since booleans can only return two values, either true or false. Helps the program make a decision.
What does the = operator mean in JavaScript?
assignment, usually when assigning a value to a variable
How do you update the value of a variable?
using the assignment operator again, don’t need to use a var keyword the second time
What is the difference between null and undefined?
null is purposeful emptiness, undefined is not purposeful emptiness. Null is declared by the developer, whereas undefined is declared by the computer.
Why is it a good habit to include “labels” when you log values to the browser console?
to make it clearer what you’re logging exactly in that line of code
Give five examples of JavaScript primitives.
string, number, boolean, null, and undefined
What data type is returned by an arithmetic operation?
number
What is string concatenation?
to join two or more strings together
What purpose(s) does the + plus operator serve in JavaScript?
add numbers or concatenate strings
What data type is returned by comparing two values (<, >, ===, etc)?
boolean
What does the += “plus-equals” operator do?
takes the variable and add something to it and then reassigns that value to the same variable.
Are strings immutable? and what does that mean?
yes - you cannot change the content of a string once it’s been created. like changing the middle letter of “cat” from a to o. it will always be a.
What are objects used for?
used to store multiple pieces of information that are related to eachother
What are object properties?
individual piece of named data within an object
Describe object literal notation.
declare object with name, assignment operator, opening curly braces for object then key value pairs separated by a comma, then closing curly braces.
How do you remove a property from an object?
delete operator
What are the two ways to get or update the value of a property?
dot notation e.g - obect.text or bracket notation - e.g. object[‘property’] = new value
What are arrays used for?
to store items in a list of information, the order of the list of information is either extremely important or unimportant
Describe array literal notation.
variable with the name for the array, assignment operator, opening square bracket, list of items in order by index separated by commas, closing square bracket.
How are arrays different from “plain” objects?
they have indexes which give their content numerical order
What number represents the first index of an array?
0
What is the length property of an array?
.length, measures the amount of items there are in an array
How do you calculate the last index of an array?
array.length - 1
What is a function in JavaScript?
a process or set of actions that have been given a name, that you can re-use by using that name.
Describe the parts of a function definition.
function keyword, name of the function, set of parentheses for parameters, curly brace, lines of code, and return statement.
Describe the parts of a function call.
function name, parentheses, arguments
When comparing them side-by-side, what are the differences between a function call and a function definition?
a function definition has a code-block and function keyword, whereas a function call doesn’t have either.
What is the difference between a parameter and an argument?
Parameter acts as a placeholder during the function definition, and the argument is the actual value during the function call.
Why are function parameters useful?
Allows you to have variance in how your code runs, apply the function to different arguments
What two effects does a return statement have on the behavior of a function?
returns back a value, as well as stop the function entirely.
Why do we log things to the console?
for debugging, verification (making sure data is what you think it is)
What is a method?
function stored as a property of an object
How is a method different from any other function?
SYNTAX! methods always have . and an object before it, functions do not.
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(indexStart, deleteCount)
How do you append or prepend an element to an array?
push or unshift
How do you break a string up into an array?
.split(where to separate or separator)
Do string methods change the original string? How would you check if you weren’t sure?
strings are immutable and can never be mutated or changed so no. But you can check with console log.
Roughly how many string methods are there according to the MDN Web docs?
36
Is the return value of a function or method useful in every situation?
no
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
Give 6 examples of comparison operators.
<, >, ==, <=, >=, !==
What data type do comparison expressions evaluate to?
Boolean
What is the purpose of an if statement?
allows us to make decisions in our code based on the result of the value of the boolean
Is else required in order to use an if statement?
Not required, but if not included - it would come back as undefined.
Describe the syntax (structure) of an if statement.
keyword if, parentheses that contains a condition, curly braces w/ code inside
What are the three logical operators?
&& (and), || (or), ! (not)
How do you compare two different expressions in the same condition?
using logical operators
What is the purpose of a loop?
a tool that allows you to run the same process over and over again
What is the purpose of a condition expression in a loop?
to check if the loop should keep going. it stops the loops.
What does “iteration” mean in the context of loops?
a single repetition of the loop
When does the condition expression of a while loop get evaluated?
Before the code block is ran
When does the initialization expression of a for loop get evaluated?
it runs one time before anything
When does the condition expression of a for loop get evaluated?
before each iteration
When does the final expression of a for loop get evaluated?
after each iteration and before the condition
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?
increases the value of the variable by 1
How do you iterate through the keys of an object?
use a for-in loop
What is JSON?
text-based format data following javascript object syntax, data interchange format
What are serialization and deserialization?
taking spread out memory, like object, and putting into text like a string. Deserialization is the opposite - taking a string and parsing it into an object. (process of taking things in order, or taking them out of order)
Why are serialization and deserialization useful?
serialization is useful because it helps put things in order and make it easier to transmit, and deserialization makes it easier to access the data
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?
localStorage.setItem(‘keyName’, value you want to assign)
How do you retrieve data from localStorage?
localStorage.getItem(‘keyName’)
What data type can localStorage save in the browser?
string
When does the ‘beforeunload’ event fire on the window object?
before the page closes
What is a method?
a function assigned to the property of an object
How can you tell the difference between a method definition and a method call?
when calling a method you use dot notation, but when defining it is within an object, and has the following structure. methodname: function ()
Describe method definition syntax (structure).
an object literal, function name then colon which assigns the function definition
Describe method call syntax (structure).
object.method(arguments)
How is a method different from any other function?
theres dot notation on methods, you need to specify which object it’s being called on or pulled from.
What is the defining characteristic of Object-Oriented Programming?
Objects can contain both data, and behavior.
What are the four “principles” of Object-Oriented Programming?
Abstraction, encapsulation, inheritance, polymorphism
What is “abstraction”?
making very complicated things seemingly simple. simplify interaction with a procedurally complex problem
What does API stand for?
Application program interface
What is the purpose of an API?
allows application to exchange data and functionality easily and securely, using a limited set of tools.
What is ‘this’ in JavaScript?
the object that you’re currently working with, the code block you’re within
What does it mean to say that this is an “implicit parameter”?
meaning 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, unless the function is currently being used - ‘this’ does not exist.
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 yet, because a function has not yet been called
Given the above character object, what is the result of the following code snippet? Why?
character.greet();
the string It’s a-me, Mario! and this is because .greet was called on character and we see that it uses the firstName property, which character has.
Given the above character object, what is the result of the following code snippet? Why?
var hello = character.greet;
hello();
undefined, because there’s no object
How can you tell what the value of this will be for a particular function or method definition?
we don’t know, because there is no value until its being used or 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 object.something
What kind of inheritance does the JavaScript programming language use?
prototype-based
What is a prototype in JavaScript?
an object with shared behavior or data that can be stored in one place and shared amongst different instances
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?
if they have a prototype
If an object does not have it’s own property or method by a given key, where does JavaScript look for it?
it goes and checks for it in each prototype object
What does the new operator do?
creates a blank plain javascript object, takes the constructor functions prototype property and puts it on the new object, then we say the newobject within the function when it runs is ‘this’. if nothing is returned - the object created in step one is returned.
What property of JavaScript functions can store shared behavior for instances created with new?
.prototype
What does the instanceof operator do?
gives you the ability to check if a specific object is a variant of a larger type of object. newObject.instanceof(originalObject)
What is a “callback” function?
a function passed through another function call 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()
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?
a positive integer that’s specific to that interval
What is AJAX?
which initially stood for Asynchronous JavaScript And XML, is a programming practice of building complex, dynamic webpages using a technology known as XMLHttpRequest.
What does the AJAX acronym stand for?
Asynchronous JavaScript And XML
Which object is built into the browser for making HTTP requests in JavaScript?
XML HTTP request
What event is fired by XMLHttpRequest objects when they are finished loading the data from the server?
‘load’ event
Bonus Question: An XMLHttpRequest object has an addEventListener() method just like DOM elements. How is it possible that they both share this functionality?
prototype
What is a client?
a piece of software that requests service or tool (initiator of a request)
What is a server?
a provider of the actual content, server responds to a clients requests
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 url, and http version
What three things are on the start-line of an HTTP response message?
protocol version (http version), status code, status text
What are HTTP headers?
additional meta data describing the request or response being made
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, it’s an optional addition where you can give some additional information.
What is a code block? What are some examples of a code block?
Code surrounded by curly braces. Ex: if statement, function, for loop
What does block scope mean?
the block scope restricts the variable that is declared inside to a specific block
What is the scope of a variable declared with const or let?
block-scope
What is the difference between let and const?
let can be reassigned, but const cannot be reassigned
Why is it possible to .push() a new value into a const variable that points to an Array?
a const variable is still mutable if it’s an array or object
How should you decide on which type of declaration to use?
if you want to be able to reassign the variable then use let, if you want to keep it constant and not reassign it use const
What is the syntax for writing a template literal?
with ticks like ` and to put variables in ${} so for example var string = hello ${variable}
What is “string interpolation”?
At this point, a template literal is just like a better version of a regular JavaScript string. The big difference between a template literal and a regular string is substitutions.
The substitutions allow you to embed variables and expressions in a string. The JavaScript engine will automatically replace these variables and expressions with their values. This feature is known as string interpolation.
What is destructuring, conceptually?
how to get property values or array elements all in one line
What is the syntax for Object destructuring?
variable initializer keyword, opening curly brace, key names, closing curly brace, assignment operator, and the object you’re pulling the data from.
const { title, author, libraryID } = book1;
What is the syntax for Array destructuring?
variable initializer keyword, opening curly brace, indexes separated by commas, closing curly brace, assignment operator, and the array you’re pulling the data from.
const [book3, book4, book5] = library;
How can you tell the difference between destructuring and creating Object/Array literals?
if curly braces or square brackets are on left side of assignment operator then you are destructuring
What is the syntax for defining an arrow function?
initializing keyword and function name, assignment operator, parameters, arrow, then code block
let thisFunction = (parameters) => {}
When an arrow function’s body is left without curly braces, what changes in its functionality?
When you omit the curly braces you don’t need to have a return statement
How is the value of this determined within an arrow function?
the parent function of the arrow function determines what this is. Usually this is figured out at the time of the function call, but when it comes to arrow functions it’s when the function is defined.
What is a CLI?
command-line interface
What is a GUI?
graphical user interface
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 - displays manual
cat - displays text for a file
ls - lists directory contents
pwd - print working directory, tells you which folder you’re in
echo - display line of text
touch - change file timestamps/create file
mkdir - creates a new directory
mv - renames a directory
rm - deletes a file only unless you use -r
cp - copies files an directories
What are the three virtues of a great programmer?
laziness, impatience, and hubris
What is Node.js?
an asynchronous event-driven JavaScript runtime
What can Node.js be used for?
allows you to run JavaScript outside of the browser, it can be used for building the backend
What is a REPL?
Read - Eval - Print Loop // it will accept individual lines of user input, evaluate those inputs according to a user-defined evaluation function, then output the result.
When was Node.js created?
2009, by Ryan Dahl
What back end languages have you heard of?
Ruby, php, python, c++, cc, java, assembly, c#, JavaScript,
What is the process object in a Node.js program?
The process object is a global object that provides information about, and control over, the current Node.js process. Data model of the node program that’s currently running.
How do you access the process object in a Node.js program?
As a global object, it is always available to Node.js applications without using require(). It can also be explicitly accessed using require():
const process = require(‘process’);
What is the data type of process.argv in Node.js?
an array of arguments
What is a JavaScript module?
It’s an object thats essentially one .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.
process & console
What is a module wrapper?
(function(exports, require, module, __filename, __dirname) {
// Module code actually lives in here
});
What is the purpose of module.exports in a Node.js module?
to store it in a global-like object that way you’re able to export it to other modules
How do you import functionality into a Node.js module from another Node.js module?
using require on the Node.js module you wish to export to
What is the JavaScript Event Loop?
basically an entity that controls what’s being processed by the system, if the stack is empty it will pull things from the task queue
What is different between “blocking” and “non-blocking” with respect to how code is executed?
blocking code needs to be executed before moving on to the next one, nonblocking doesnt and can be ran asynchronously. Anything occupying the call-stack is blocking.
What is a directory?
a special file that lists other files and directories
What is a relative file path?
relative file path tells you how to get to a file from your current location
What is an absolute file path?
location of a file from the root directory
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?
writeFile
Are file operations using the fs module synchronous or asynchronous?
both
What is a client?
the requestor of the service (a program or device that sends requests to a server)
What is a server?
the provider of the service (a program or device that receive the request from a client and return an service)
Which HTTP method does a browser issue to a web server when you visit a URL?
GET
What is on the first line of an HTTP request message?
http method, request target, http version
What is on the first line of an HTTP response message?
protocol version, status code, status text
What are HTTP headers?
area of http request or response that passes additional info in metadata about the request or response
Is a body required for a valid HTTP message?
No
What is NPM?
a website, package registry, and a CLI
What is a package?
directory with one or more files, and a package.json
How can you create a package.json with npm?
npm init –yes
What is a dependency and how to you add one to a package?
dependency is a piece of software that your software is going to need, you can add it by doing “npm install “software””
What happens when you add a dependency to a package with npm?
updates package.json to include dependency and the package is downloaded from the npm registry to node_modules
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?
app.listen()
How do you mount a middleware with an Express application?
by calling the use method of the app object. app.use();
Which objects does an Express application pass to your middleware to manage the request/response lifecycle of the server?
req and 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?
This method is used to parse the incoming requests with JSON body and is based upon the bodyparser. You would need it when you want to receive JSON data and add it to a data model
What is the significance of an HTTP request’s method?
it defines the action to be performed
What is PostgreSQL and what are some alternative relational databases?
relational database management system, mySQL, SQL by microsoft, oracle
What are some advantages of learning a relational database?
theyre often free, and widely used. very important to learn the further you get into your career
What is one way to see if PostgreSQL is running?
sudo service postgresql status
What is a database schema?
schema defines the structure of how we’re going to be storing our data
What is a table?
list of rows, each having the same attributes
What is a row?
one item in the table - has all the column values.
What is SQL and how is it different from languages like JavaScript?
structure query language, primary way of interacting with relational databases. it’s different because it’s a declarative language
How do you retrieve specific columns from a database table?
select statement with select keyword, column names in quotes, and separated by commas, then the name of the table you want to get it from.
How do you filter rows based on some specific criteria?
using where keyword
What are the benefits of formatting your SQL?
makes it easier to read when your queries get longer
What are four comparison operators that can be used in a where clause?
=, !=, <, >
How do you limit the number of rows returned in a result set?
limit keyword followed by a number
How do you retrieve all columns from a database table?
select * from tablename
How do you control the sort order of a result set?
order by “column name” desc or ascending
How do you add a row to a SQL table?
instert into “tablename” (“columnName”, “columnName”)
values (‘values’, ‘values’)
returning *;
What is a tuple?
a list of values with a specific order
How do you add multiple rows to a SQL table at once?
by adding more sets of parentheses for values
How do you get back the row being inserted into a table without a separate select statement?
returning “columnNames”
How do you update rows in a database table?
update “actors”
set “firstName” = ‘Baby’,
“lastName” = ‘Yoda’
where “actorId” = 15;
Why is it important to include a where clause in your update statements?
if you don’t, it will update every row in the table
How do you delete rows from a database table?
delete
from “cities”
where “name” = ‘Pyongyang’
returning *;
How do you accidentally delete all rows from a table?
Not including where
What is a foreign key?
a value with a column in one table
How do you join two SQL tables?
select “firstName”,
“lastName”
from “customers”
join “payments” using (“customerId”)
How do you temporarily rename columns or tables in a SQL statement?
using “as”
What is the purpose of a group by clause?
to group rows together so you can apply an aggregate function to a group
What are some examples of aggregate functions?
count, sum, max, min, avg
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?
promise.then( value => {
console.log(value)
}
How do you handle the rejection of a Promise?
promise.catch(error => {
console.error(error)
}
What is Array.prototype.filter useful for?
What is Array.prototype.reduce useful for?
if you want to access the contents of an array of objects, but you want to do it repeatedly
What is Array.prototype.map useful for?
What is “syntactic sugar”?
an alternate syntax that’s meant to be easier to understand
What is the typeof an ES6 class?
function
Describe ES6 class syntax.
class ClassName {
constructor(…) {
stuff
}
method name() {
stuff
}
Dont need a constructor unless you have arguments you want to pass in
What is Webpack?
node.js framework that allows you to bundle your javascript modules
How do you add a devDependency to a package?
–save-dev
What is an NPM script?
a way to bundle common shell commands
How do you execute Webpack with npm run?
npm run build
How are ES Modules different from CommonJS modules?
not using the require method, using import from. and export using export default
What kind of modules can Webpack support?
ecmascript, commonjs, AMD modules, aseets, webassembly modules
What is React?
React is a JavaScript library for building user interfaces.
React is used to build single-page applications.
React allows us to create reusable UI components.
What is a React element?
React element is the smallest renderable unit available in React. React elements are simple javascript objects
How do you mount a React element to the DOM?
target the container, then create a root using createRoot, then call the .render method of the root object with the element as the argument that you want to append basically
What is Babel?
Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments.
What is a Plug-in?
is a software component that adds a specific feature to an existing computer program. Enables customization.
What is a Webpack loader?
Loaders are transformations that are applied to the source code of a module. They allow you to pre-process files as you import or “load” them. Thus, loaders are kind of like “tasks” in other build tools and provide a powerful way to handle front-end build steps. Loaders can transform files from a different language (like TypeScript) to JavaScript or load inline images as data URLs
How can you make Babel and Webpack work together?
by using the babel loader
What is JSX?
extension of javascript syntax, allows you to write HTML within a JS file.
Why must the React object be imported when authoring JSX in a module?
The JSX code wont work if you dont import it, due to the react.createElement
How can you make Webpack and Babel work together to convert JSX into valid JavaScript?
babel loader, and babelplugin
What is a React component?
a function with reusable code that returns react elements
How do you define a function component in React?
by writing a function that will return jsx
How do you mount a component to the DOM?
target the container, then create a root using createRoot, then call the .render method of the root object with the element as the argument that you want to append basically
What are props in React?
Props are arguments passed into React components.
How do you pass props to a component?
Props are passed to components via HTML attributes.
How do you write JavaScript expressions in JSX?
using curly braces within your JSX
How do you create “class” component in React?
class CustomButton extends React.Component {
render(props) {
return <button>{this.props.text}</button>;
}
}
How do you access props in a class component?
this.props.name
What is the purpose of state in React?
allows us to manage changing data in an application
How to you pass an event handler to a React element?
through attributes
What are controlled components?
the component itself is managing the state of the component, everything related to it is being controlled by react
What two props must you pass to an input for it to be “controlled”?
value attribute, and onChange attribute
What Array method is commonly used to create a list of React elements?
array.map
What is the best value to use as a “key” prop when rendering lists?
a unique identifier, something like an Id
What does express.static() return?
middleware, a function
What is the local __dirname variable in a Node.js module?
the name of the current module
What does the join() method of Node’s path module do?
takes in a series of paths as arguments as combines them into one
What does fetch() return?
a promise .then()
What is the default request method used by fetch()?
GET
How do you specify the request method (GET, POST, etc.) when calling fetch?
by adding a method parameter
When does React call a component’s componentDidMount method?
right after the component is mounted
Name three React.Component lifecycle methods.
constructor, render, componentDidMount, componentDidUpdate, componentWillMount
How do you pass data to a child component?
using props