Section 2 Flashcards
What is a code block? What are some examples of a code block?
- denoted by curbraces
- if/else, for, do while, while, try, catch, etc
What does block scope mean?
- inside the code block
- things that happen inside the curbraces
What is the scope of a variable declared with const or let?
block-scope
- var uses global (the window global object)
- var is FUNCTION scoped
- let is not attached to the global object
- let is BLOCK-SCOPED, not initialized to any value, and not attached to the global object.
What is the difference between let and const?
- let is mutable, can be reassigned, and doesn’t have to be initialized
- const is read-only/constant, can’t be reassigned, but can be modified, is not immutable, must have initialization
- by convention, the constant identifiers are in uppercase.
const CONSTANT_NAME = value;
Why is it possible to .push() a new value into a const variable that points to an Array?
- bc we’re not reassigning a block-scope, we’re just modifying the array held by the const variable
- const’s values can change/be mutated, but it cannot be reassigned to a dif block-scope value
How should you decide on which type of declaration to use?
is the whole variable being reassigned (let), or are just the values inside the variable changing (const)
arrays & objects, always CONST
What is the syntax for writing a template literal?
backticks: this is a template literal
What is “string interpolation”?
imbedding variables & expressions in a string and JS automatically replacing them with their values
it looks like ${variable_name} this
__code read: ___
const bio = My name is ${firstName} ${lastName} and I am ${age} years old.
;
there is a template literal string with the substitutions firstName, lastName, and age, being assigned to the const bio
What is destructuring, conceptually?
- a way to assign the properties of an object to individual variables
- to get values from an object
What is the syntax for Object destructuring?
let { propertyName: variableName, propertyName: variableName } = sourceObject;
so ‘sourceObject.propertyName’ is now ‘variableName’ for ease of use
Object destructuring assigns the properties of an object to variables with the same names by default.
What is the syntax for Array destructuring?
let [var, for, each, index] = scrArray/srcFunc()
How can you tell the difference between destructuring and creating Object/Array literals?
assignment is inverted
creating, on the right
destructuring, on the left
code read:
const { title, author, libraryID } = book1;
const { title: eek, author: barba, libraryID: durkle } = book2;
the const title, author, libraryID are being destructured from book1
the const title is being aliased with eek … being destructured from boook2
What is the syntax for defining an arrow function?
parameter list, arrow, codeblock
let funcName = (parameter) => { return expression; };
When an arrow function’s body is left without curly braces, what changes in its functionality?
- it will return automatically
- implicit/implied return = withOUT curbraces
- explicit return = WITH cubraces
How is the value of THIS determined within an arrow function?
- from the enclosing lexical scope. so you cannot use a new this in an arrow function, unless you:
- assign the this to a variable, then use that variable in your arrow function
- this in an arrow func captures this’s value from the enclosing context instead of creating its own
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 – interface to the online reference manuals
cat – concat files & print to standard output, but rly for viewing file contents
_cat filename -quickly see the contents of a file
ls – list directories
pwd – print working directory
echo – display a line of text
touch – change file timestamps, but rly for creating empty files
_touch empty-file.txt -create an epmty file
mkdir – make directories
mv – move (rename) files
rm – remove files/directories
cp – copy files/directories
What are the three virtues of a great programmer?
- Laziness: The quality that makes you go to great effort to reduce overall energy expenditure. It makes you write labor-saving programs that other people will find useful and document what you wrote so you don’t have to answer so many questions about it.
- Impatience: The anger you feel when the computer is being lazy. This makes you write programs that don’t just react to your needs, but actually anticipate them. Or at least pretend to.
- Hubris: The quality that makes you write (and maintain) programs that other people won’t want to say bad things about.
What is Node.js?
- a js environment outside of a browser
- can be used to build a server
a program that allows JavaScript to be run outside of a web browser, especially for talking/building to backend/servers/etc as a foundation for a web application
What can Node.js be used for?
building servers or backends for web applications
What is a REPL?
Read–eval–print loop
A read–eval–print loop (REPL), also termed an interactive toplevel or language shell, is a simple interactive computer programming environment that takes single user inputs, executes them, and returns the result to the user.
What is the process object in a Node.js program?
- a global variable that gives info about the current node.js process
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?
- same way you would any object ?
- through node in the terminal
- through node in the terminal executing js file with a console.log of the object/properties
As a global, 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 strings
What is a JavaScript module?
- a single .js file, full of code that interacts with other modules full of code to create a cohesive application
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
- setinterval
- settimeout
- process
What is the purpose of module.exports in a Node.js module?
- insures that the code in the module is able to be seen & accessed (connected to) by other modules in the application
How do you import functionality into a Node.js module from another Node.js module?
- with require()
What is the JavaScript Event Loop?
- js’s logical ordering of what it’s supposed to do
- a continual loop of checking the call stack and executing functions
What is different between “blocking” and “non-blocking” with respect to how code is executed?
- whether or not a process impedes other processes
- non-blocking will offset that stuff to do other things until it’s the slow thing is ready
- blocking would allow the slow thing to impede otehr things
The Event Loop is one of the four major concepts that sets JavaScript apart from many other languages.
- Prototypal Inheritance
- how this works
- closures
- the event loop
Understanding how asynchronous programming works is absolutely critical to modern Web development and especially programming in JavaScript.
What is a directory?
a folder that holds files/a repository
What is a relative file path?
relative to where you are locally
What is an absolute file path?
the full path on the system, relative to root
What module does Node.js include for manipulating the file system?
fs (file system)
What method is available in the Node.js fs module for writing data to a file?
.writeFile() method
Are file operations using the fs module synchronous or asynchronous?
asynchronous
What is a client?
- a requester of a service or resource provided by a server
What is a server?
- a provider of a service or resource
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?
- an HTTP method; GET, PUT, POST, etc
- the request target; URL or absolute path, port etc
- the HTTP version
A start-line describing the requests to be implemented. This start-line is always a single line.
What is on the first line of an HTTP response message?
- the protocol version, usually HTTP/1.1
- a status code indicating success/failure; 404, 200 etc
- a status text, brief info for the humans
A status-line describing whether successful or a failure. This start-line is always a single line.
What are HTTP headers?
optional specification info
Is a body required for a valid HTTP message?
nope. optional
What is NPM?
- Node Package Manager
- a way to re-use code from other devs, or share your code for use
- consists of:
- website, use to discover packages, set up profiles, and manage other aspects of your npm experience.
- CLI, runs from a terminal, and is how most developers interact with npm.
- registry, a large public database of JavaScript software and the meta-information surrounding it.
What is a package?
- bits of reusable code, also called modules
- a directory with files that also has package.json
How can you create a package.json with npm?
- make sure you’re in the correct directory, then:
- npm init –yes
What is a dependency and how to you add one to a package?
- a connection to a library of code your program will access/use
- npm install ‘package-name’
- npm uninstall ‘package-name’
What happens when you add a dependency to a package with npm?
- it’s installed into the node-modules folder in the directory where it’s created
- it’s added to the dependencies object
How do you add express to your package dependencies?
- be in the correct directory
- npm init –yes to make a new package.json to hold it
- 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()
const express = require('express'); const app = express();
app.use((req, res) => { // eslint-disable-next-line no-console console.log('req.method: ', req.method); res.send('a string'); });
Which objects does an Express application pass to your middleware to manage the request/response lifecycle of the server?
- Request, req
- Response, res
- next()
What is the appropriate Content-Type header for HTTP messages that contain JSON in their bodies?
- application/json
What is the significance of an HTTP request’s method?
- gives a way to indicate our intention between client/server
- the methods only do the thing they say if WE BUILD THEM to do those things
What does the express.json() middleware do and when would you need it?
- it will allow app to parse JSON request bodies
- you need it when you’re expecting incoming POST requests
What is PostgreSQL and what are some alternative relational databases?
- Postgre is a standalone, isolated application we interact with through an API
- Structured Query Language
- a relational database management system (RDBMS)
- spreadsheeeeeets
_PostgreSQL is a powerful, free, open source Relational Database Management System
_MySQL (also free), SQL Server by Microsoft, and Oracle by Oracle Corporation, Amazon has one…
What are some advantages of learning a relational database?
- RDBs are stronk pwrful
- very common, widely used for just about everything where stored data is relational (inter-related data)
- many kinds of SQL db used, knowing SQL gives you access to them all
_A quality of many relational databases is that they support good guarantees about data integrity. They can store and modify data in a way that makes data corruption as unlikely as possible. This means that developers can set up their database to reject “bad” data and not worry about data being “half written”.
What is one way to see if PostgreSQL is running?
sudo service postgresql status
What is a database schema?
- a collection of tables that defines how the db 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 list of rows each having the same set of attributes
[1 x A|B|C|D|E]
[2 x A|B|C|D|E]
…etc
What is a row?
- an item in a db/entry in the table which has values in the columns
What is SQL and how is it different from languages like JavaScript?
- Structured Query Language is the primary way of interacting with relational databases
- a relational database management system (RDBMS)
- spreadsheeeeeets
- JS is an IMPERATIVE high lvl OOP language for front end design and back end intergration/communication (you tell it explicitly what to do)
- SQL is for managing relational databases
- SQL is DECLARATIVE (like HTML & CSS, you tell it what you want and it tries to produce that)
_Relational databases interpret SQL and then dynamically generate a plan of action to perform the programmer’s commands as efficiently as possible.
How do you retrieve specific columns from a database table?
select “column01Name”,
“column02Name”
from “tableName”;
How do you filter rows based on some specific criteria?
select "colName", "colName2", "colName3" from "tableName" where "colName" = 'columnValue'
ex:
select “ISBN”
from “books”
where “coverArt” = ‘blue’;
- text values (‘blue’) are single quote
- numbers & booleans don’t need the single quotes, but will work if used
- in addition to =, can use , !=
- will be random w/out an “order by” clause
What are the benefits of formatting your SQL?
everything is better in a nice tidy order
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?
select “colName”
from “tableName”
order by “colName” desc
limit 1;
desc changes to descending order instead of ascending, so this -^- bit will return the one most expensive thing/highest value from that possible list
How do you retrieve all columns from a database table?
select *
from “tableName”;
-the results order will be random, but it will be all columns
How do you control the sort order of a result set?
select *
from “tableName”
order by “columName”;
-will return all columns in ascending order of specified column’s value
How do you add a row to a SQL table?
insert into “tableName” (“column1”, “column2”, “column3”)
values (‘value1’, ‘value2’, value 3)
returning *;
_ returning *; will immediately return/display the row you just inserted (can use list instead of *)
_‘productID’ column/value ommited bc tables are often configured to auto-generate identifier attributes to avoid accidental duplicates
What is a tuple?
a list of values
How do you add multiple rows to a SQL table at once?
same as a single row, just with a comma making a list of lists
insert into “tableName” (“column1”, “column2”, “column3”)
values (‘value1’, ‘value2’, value 3),
values (‘valueA’, ‘valueB’, value C)
returning *;
How do you get back the row being inserted into a table without a separate select statement?
returning *; at the bottom of the insert statement
How do you update rows in a database table?
update “tableName”
set “columnName” = newValue
where “colValue” = value;
update “products”
set “price” = 100
where “productId” = 24;
_can update multiple columns with comma-list like so:
update “products”
set “price” = 200,
“name” = ‘Super ShakeWeight’,
“description” = ‘Makes you ULTRA strong!’
where “productId” = 24;
Why is it important to include a where clause in your update statements?
so you don’t change ALL the things, just the thing you want to change
How do you delete rows from a database table?
delete from “tableName”
where “columnName” = value;
delete from “products”
where “productId” = 24
returning *;
_we can also use AND:
If we wanted to delete all “products” in the ‘cleaning’ category that are cheaper than 20, we would:
delete from “products”
where “category” = ‘cleaning’
and “price” < 20
How do you accidentally delete all rows from a table?
delete from “tableName”;
foreign key constraint:
- when you try to delete a thing from a table but it says no bc it’s being referenced in another table
- failsafe to prevent accidentally breaking tables
What is a foreign key?
a column + values shared by multiple tables
How do you join two SQL tables?
select *
from “table01”
join “tables2” using (“sharedColumnName”);
select *
from “products”
join “suppliers” using (“supplierId”);
How do you temporarily rename columns or tables in a SQL statement?
select the table.columns, use AS to temp rename them
select “table”.”columnNameX” AS “tempName”
“table2”.”columnNameX” as “difTempName”
from “table”
join “table2” using (“sharedColName”);
select “products”.”name” as “product”,
“suppliers”.”name” as “supplier”
from “products”
join “suppliers” using (“supplierId”);
_this will only change their names for the immediate output results
What are some examples of aggregate functions?
max(), avg(), count(), min(), sum(), every()
ex:
select max("price") as "highestPrice" from "products";
select avg("price") as "averagePrice" from "products";
select count(*) as "totalProducts" from "products";
What is the purpose of a group by clause?
to apply aggregate functions to selections of rows
ex:
select “category”,
avg(“price”) as “averagePrice”
from “products”
group by “category”;
-will give the avg price for each product category
what exactly is a Promise?
- The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
It’s a a proxy for a value not necessarily known when the promise is created.
Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.
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.
–once either fulfilled or rejected it’s state can no longer change
How do you handle the fulfillment of a Promise?
then(fulfillmentFunc(), rejectionFunc())
promise. then(console.log, console.error)
promise. the(resolve, reject)
p.then(onFulfilled[, onRejected]);
p.then(value => { // fulfillment }, reason => { // rejection });
How do you handle the rejection of a Promise?
with second callback in then(), or with catch()
promise. then(console.log).catch(console.error)
p. catch(onRejected);
p.catch(function(reason) { // rejection });
What is Array.prototype.filter useful for?
- filter an array and create a new array from what’s gathered
_The filter() method creates a new array with all elements that pass the test implemented by the provided function.
_filter() calls a provided callbackFn function once for each element in an array, and constructs a new array of all the values for which callbackFn returns a value that coerces to true.
What is Array.prototype.map useful for?
- apply some logic to every index of an array, and return a new array of the results
- can duplicate arrays with or without data transformation
- will always be of equal length
_The map() method 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?
- to create a single value from all values in an array
_The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) — until there are no more elements to add.
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 Name { optionalConstructor(params) { this.paramPropName = param; } prototypeMethodDefinition() { const { paramPropName } = this; return `${paramPropName}`; } }
_ex: class Rectangle { constructor(height, width) { this.height = height; this.width = width; } }
What is “refactoring”?
- ‘improving’ the design of the code
_In computer programming and software design, code refactoring is the process of restructuring existing computer code—changing the factoring—without changing its external behavior. Refactoring is intended to improve the design, structure, and/or implementation of the software (its non-functional attributes), while preserving its functionality.
What is Webpack?
- compiles/combines JS files into a single file
_a tool that lets you bundle your JavaScript applications (supporting both ESM and CommonJS), and it can be extended to support many different assets such as images, fonts and stylesheets.
How do you add a devDependency to a package?
- npm install devDependency –save-dev
–prod-dev is the default
What is an NPM script?
- a shortcut to larger scripts
- any CLI command can be made into a script and executed with it’s shortcut
- a small bit of js code tucked into an object property in the package.json file
- you can access it with:
npm run scriptName
_ex: {... "scripts": { "build": "webpack" } } npm run build
How do you execute Webpack with npm run?
- go into package.json and add a script key/val pair where key = scriptName & value = webpack
- in cmdr, nmp run scriptName
devDependency - tools used indirectly to DEV the code
dependency - tools used directly IN the code
webpack & webpack-cli ALWAYS go together
when cloning a new repo always open up package.json and read the scripts to see what scripts & dependencies are there to use
How are ES Modules different from CommonJS modules?
const TodoList = require('./todo-list'); module.exports = TodoApp;
vs
import TodoList from ‘./todo-list’;
export default TodoApp;
- Their syntax is even more compact than CommonJS’s.
- Their structure can be statically analyzed (for static checking, optimization, etc.).
- Their support for cyclic dependencies is better than CommonJS’s.
- Similar to CommonJS, they have a compact syntax, a preference for single exports and support for cyclic dependencies.
- Similar to AMD, they have direct support for asynchronous loading and configurable module loading.
What kind of modules can Webpack support?
CommonJS & ES6 and others
What is React?
- a JS library for creating user interfaces
- built with JS, doesn’t do anything you couldn’t do on your own, but it’s pre-built
What is a React element?
- a plain object, uses a virtual DOM (which is just a bunch of objects) to update the actual DOM (which is also just a bunch of objects)
const bucket = React.createElement( 'h1', null, 'Hello, React!' );
How do you mount a React element to the DOM?
ReactDOM.render(element, container);
-any size project only ever calls ReactDOM.render ONCE
What is Babel?
- a fancy tool for working across dif versions of JS
_Babel is a JavaScript compiler
_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?
_a set of software components that adds specific abilities to a larger software application
_a software component that adds a specific feature to an existing computer program. When a program supports plug-ins, it enables customization.
What is a Webpack loader?
- they allow you to pre-process files as you import or “load” them
- you can install loaders for various specific things (CSS, TypeScript, etc) and then assign all files of those types to be processed by a given 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. Loaders even allow you to do things like import CSS files directly from your JavaScript modules
How can you make Babel and Webpack work together?
- installing babel-loader devDependency
What is JSX?
- a syntax extension for JavaScript which produces React elements
_Fundamentally, JSX just provides syntactic sugar for the React.createElement(component, props, …children) function.
Why must the React object be imported when authoring JSX in a module?
- bc all JSX turns into React.createElement calls, so yeah
How can you make Webpack and Babel work together to convert JSX into valid JavaScript?
devDependencies:
- babel-loader
- @babel/core
- @babel/plugin-transform-react-jsx
- webpack
- webpack-cli
What is a React component?
- reusable React code that describes a p
- basically JS function that takes an object (properties) as an argument and returns React elements for the DOM
_Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.
How do you define a function component in React?
unction Welcome(props) { return <h1>Hello, {props.name}</h1>; }
This function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element. We call such components “function components” because they are literally JavaScript functions.
You can also use an ES6 class to define a component:
class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } }
Always start component names with a capital letter.
React treats components starting with lowercase letters as DOM tags. For example, <div> represents an HTML div tag, but represents a component and requires Welcome to be in scope.</div>
How do you mount a component to the DOM?
// React 17 version: // ReactDOM.render(, document.querySelector('#root'));
- first you need a DOM element to aim it at, like a div classed as ‘root’
- make the component
- select the DOM el with .getElById and use as arg inside ReactDOM.creatRoot, assign result to const root
- root.render();
function Welcome(props) { return <h1>Hello, {props.name}</h1>; }
const element = ;
const root = ReactDOM.createRoot(document.getElementById(‘root’));
root.render(element);
What are props in React?
- objects of properties to use
- allows the passing of info
How do you pass props to a component?
- k/v pair on the JSX component that resembles an attribute
How do you write JavaScript expressions in JSX?
wrap em in curbraces {}
How do you create “class” component in React?
To define a React component class, you need to extend React.Component:
class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } } The only method you must define in a React.Component subclass is called render(). All the other methods described on this page are optional.
How do you access props in a class component?
- have to use THIS in the JSX
- render() { return { THIS.props.whatever } } }
What is the purpose of state in React?
- state allows us to manage changing data in an application
- STATE is a plain JavaScript object that holds info which influences the render output
_State is similar to props, but it is private and fully controlled by the component.
_state is often called local or encapsulated. It is not accessible to any component other than the one that owns and sets it.
_PROPS get passed to the component (similar to function parameters) whereas STATE is managed within the component (similar to variables declared within a function). - STATE is asynchronous
- don’t try to console.log it directly after assigning it bc it won’t be accurate
- if you want to c.log it, do it at the top of the RENDER(), bc render() is called when state updates
How to you pass an event handler to a React element?
- put it directly on the element:
- create it under the constructor in the class
- bind it to the constructor
(this. handleClick = this.handleClick.bind(this);
- assign it in the render() return ( {this.state.isClicked ? 'ON' : 'OFF'} ) ;
What Array method is commonly used to create a list of React elements?
.map()
What is the best value to use as a “key” prop when rendering lists?
IDs or values from data
What are controlled components?
- an input element whose value is controlled by the React component that renders it
What two props must you pass to an input for it to be “controlled”?
- this.handleChange
- this.handleSubmit
this. handleChange = this.handleChange.bind(this);
this. handleSubmit = this.handleSubmit.bind(this);
What does express.static() return?
_it directly returns a function, the function handles requests for files or moves on to the next file
What is the local __dirname variable in a Node.js module?
_it’s a string and it’s the absolute path to the folder the module is in
_The directory name of the current module. This is the same as the path.dirname() of the __filename.
What does the join() method of Node’s path module do?
- takes file segments and makes a file path
_The path.join() method joins all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path.
Zero-length path segments are ignored. If the joined path string is a zero-length string then ‘.’ will be returned, representing the current working directory.
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); // Returns: '/foo/bar/baz/asdf'
What does fetch() return?
- a promise which resolves to the Response object representing the response to your request.const
What is the default request method used by fetch()?
GET
How do you specify the request method (GET, POST, etc.) when calling fetch?
- in the props of the config object
fetch (url, { method: 'GET', ..., ... )};
When does React call a component’s componentDidMount method?
- immediately after a component is mounted (inserted into the tree).
Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.
This method is a good place to set up any subscriptions. If you do that, don’t forget to unsubscribe in componentWillUnmount().
Name three React.Component lifecycle methods.
__the 3 that matter most:
componentDidMount()
componentWillUnmount()
componentDidUpdate()
How do you pass data to a child component?
props