Senior Side Flashcards
es6-const-let
What is a code block? What are some examples of a code block?
A code block are lines of code which are grouped together by curly braces. Some examples are for loops, if statements, and functions.
es6-const-let
What does block scope mean?
It means that the code/variable will not be accessible outside the code block (curly braces).
es6-const-let
What is the scope of a variable declared with const or let?
Block scoped
Var = function scope
es6-const-let
What is the difference between let and const?
Let can be updated, but not redeclared. Const can’t be updated nor redeclared.
Const must be initialized when it’s defined
Similarity = both const and let are blocked scoped and they’re not initialized with undefined like var keyword.
es6-const-let
Why is it possible to .push() a new value into a const variable that points to an Array?
We can change the values, in this case add, of a const variable, but we can’t reassign or redeclare it.
es6-const-let
How should you decide on which type of declaration to use?
Const variables are for things that don’t change values, let is for values that are meant to manipulated or changed.
good code doesn’t reassing var
es6-template-literals
What is the syntax for writing a template literal?
Replace all quotes for a string with backticks ( ` ` )
Can contain strings and any JavaScript expressions (anything that returns a value): ${firstName.toUpperCase()}
es6-template-literals
What is “string interpolation”?
Having expression/variables values substituted in a string. EX: ${variable_name}
es6-destructuring
What is destructuring, conceptually?
Assigning a variable to the value extracted from an object property or an array index
es6-destructuring
What is the syntax for Object destructuring?
const keyword, then curly braces { }, property key names, then equal signs = , then object name you’re destructuring from, use OR || to avoid errors after name
es6-destructuring
What is the syntax for Array destructuring?
const keyword, then square brackets [ ], elements you want, then equal signs = array name that is destructured, use OR || to avoid errors after name
es6-destructuring
How can you tell the difference between destructuring and creating Object/Array literals?
variable name at start(left)= creating literals
variable name at end(right) = destructuring literals
es6-arrow-functions
What is the syntax for defining an arrow function?
optional variable declaration, assignment operator, optional params (if 0 param then no parenthesis, if 1 param optional parenthesis, more than 1 then parentheses is needed), arrow, then a single expression or a code block
es6-arrow-functions
When an arrow function’s body is left without curly braces, what changes in its functionality?
it returns (implicitly) from the function
If using expression like ‘x + y’, then ‘return’ keyword/statement not needed.
Note: expression has a result value. statement doesn’t have a result, it is more of a command
If using curly braces then it needs ‘return’ keyword/statement.
Note: in react (expression-based) if put statement into where expression should be then it will error
es6-arrow-functions
How is the value of ‘this’ determined within an arrow function?
better to look at it as when is ‘this’ determined.
Arrow functions captures the ‘this’ value of the enclosing context rather than making its own ‘this’ (similar to how scope works)
arrow functions: ‘this’ is defined at function definition
traditional functions: ‘this’ is defined at function call
Note: in the example exercise, the setTimeout functions are being defined multiple times when the function runs (‘this’ is the jokester object with the arrow functions in setTimeout)
Note2: to bypass ‘this’ being window object when undefined (global ‘this’) then you assign ‘this’ to a variable. For example: ‘var realThis = this’
Note3: if you made the functions of the properties of jokester using ‘traditional ES5 functions’ then it would grab the global ‘this’ object because ‘this’ will be defined at function call
Note4: function names AND values are hoisted to the top, while var names are hoisted, but their values aren’t evaluated till JavaScript reaches their code line. Tim’s tip: Create functions and vars where you need them, then you can move the functions/variables around (like using utility functions at the bottom)
command-line-basics
What is a CLI?
Stands for command-line interface.
It processes commands to a computer program in the form of lines of text
command-line-basics
What is a GUI?
Stands for graphical user interface.
It is a form of user interface that allows users to interact with electronic devices through graphical icons and audio indicator such as primary notation. Example of GUI text editor is VS Code
command-line-basics
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: review what a command does (manual)
cat: print out contents of a file into terminal or combine contents of a file.
ls: list files in a current directory (can go to other directories if using path)
pwd: print current working directory
echo: display a line of text (string) into terminal, which can be added to a new file
touch: create a new file in current directory (if you use path then you can create the file in another directory)
mkdir: create a new directory
mv: move or rename a file (renaming something also moves it)
rm: remove/delete a file or directory (there is no undo and it doesn’t go into the trash)
cp: copy a file, which you can rename in the same line
command-line-basics
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.
node-intro
What is Node.js?
A back-end JavaScript runtime environment (program) that operates on the Chrome V8 engine and executes JavaScript code outside of a browser.
node-intro
What can Node.js be used for?
Node.js can be used to execute JavaScript outside of the web browser. Develop command-line applications, server applications, and other back-ends.
node-intro
What is a REPL?
Stands for read, evaluate, print, and loop (loop because it waits for next input). It’s a computer environment where you can write code and execute code.
node-intro
When was Node.js created?
Node.js was created on May 27, 2009
node-intro
What back end languages have you heard of?
JavaScript (node.js), ruby, python, php, c# (.NET), perl, typescript, assembly, go, sql (for programming databases), haskell (only has functions (has to return something) and data, Tim said it changed the way he wrote JavaScript in a good way)
Scripting Languages (often interpreted): ruby, python, php, javascript, perl
Compiled Languages (analyzes source code then makes new set of code): c, c++, go, haskell, c# (.NET), f#, java, assembly (maybe compiled??), typescript
sql on it’s own
node-process
What is a computer process?
The instance of a computer program that is being executed by one or many threads. It contains the program code and its activity.
short version: instance of running program
node-process
Roughly how many computer processes are running on your host operating system (Task Manager or Activity Monitor)?
500+ processes, but only 3 were listed as running
node-process
Why should a full stack Web developer know that computer processes exist?
Full stack web development is based on making multiple processes work together to form one application, so knowing about computer processes will help with making applications with clients, servers, and databases
node-process-argv
What is the ‘process’ object in a Node.js program?
It’s a global object that provides information about, and control over, the current Node.js process.
Another way: a model of the current instance of Node.js process
node-process-argv
How do you access the ‘process’ object in a Node.js program?
The 'process' object is always available (global) to Node.js applications, so you can just type 'process.' To explicitly access it then you use: const process = require('process');
node-process-argv
What is the data type of ‘process.argv’ in Node.js?
An array of strings which contains the command line arguments passed when the Node.js process was launched.
Note: means array of strings.
Note: the first element will be ‘process.execPath’ (the absolute path to where the Node.js process launched), the second element will be the name of the JavaScript file being executed, the remaining elements are any additional command line arguments.
node-module-system
What is a JavaScript module?
A JavaScript file…. which uses code from a separate file to execute its code
node-module-system
What values are passed into a Node.js module’s local scope?
‘export’ = a reference to module.exports (you can add a single thing by making it exports = ‘some string’, but its default value is an object, so an example is exports.foo = ‘bar’, which will add them as a property of the exports object)
‘require’ = used to import modules, JSON, and local files.
‘module’ = a reference to the current module
‘__filename’ = file name of the current module
‘__dirname’ = directory name of the current module
These 5 values (all local variables or parameters which are passed into a module wrapper function to know where your code is from) are passed into your module, which can then be accessed by your code
node-module-system
Give two examples of truly global variables in a Node.js program.
The ‘process’ object and the ‘global’ namespace object. ‘console’ is also another one.
In JavaScript the window object controls both variables and their process
In Node.js, the ‘process’ object controls processes and the ‘global’ object controls variables
node-require
What is the purpose of module.exports in a Node.js module?
To export the code in one JavasScript file and give access to that code to other JavaScript files
node-require
How do you import functionality into a Node.js module from another Node.js module?
const variableName
= require FUNCTION followed by parenthesis, which contains a string to the relative path of the file you want to import
the-event-loop
What is the JavaScript Event Loop?
It’s responsible for handling callbacks. Looks at the stack, if it’s clear, then look at the task/callback queue, and then push the callback onto the stack
the-event-loop
What is different between “blocking” and “non-blocking” with respect to how code is executed?
blocking = operations that run synchronously (and are slow, which block further execution of JavaScript code (ex; AJAX requests)
blocking operations are happening on the stack and nothing can be executed until it is off the stack - JavaScript causes
non-blocking = operations that run asynchronously and therefore don’t block execution of JavaScript code (gets put into the callback queue)
non-blocking operations happen anywhere that’s not on stack
Note: a callback queue exists which means callbacks will not execute all at once
node-fs-readfile
What is a directory?
a file folder
node-fs-readfile
What is a relative file path?
The file path relative from the current/or some location
node-fs-readfile
What is an absolute file path?
The full path, starting from the root (in mac OS it is a slash), of a file
node-fs-readfile
What module does Node.js include for manipulating the file system?
the ‘fs’ module
stands for file system
node-fs-writefile
What method is available in the Node.js fs module for writing data to a file?
fs.writeFile() method
node-fs-writefile
Are file operations using the fs module synchronous or asynchronous?
The ones we used are asynchronous, but there are synchronous versions
http-messages-recap
What is a client?
Service requesters - software/hardware that request info from servers
http-messages-recap
What is a server?
service providers: software/hardware that provides resource or service
note: nowadays it’s software talking to each other isntead of hardware/computer devices
http-messages-recap
Which HTTP method does a browser issue to a web server when you visit a URL?
GET method - which requests representation of data
http-messages-recap
What is on the first line of an HTTP request message?
The request header, HTTP method which describes action to be performed (GET) and then the request target (URL), protocol version
http-messages-recap
What is on the first line of an HTTP response message?
status line, with the protocol/http version and then the status code, then status text
http-messages-recap
What are HTTP headers?
Information relating to the HTTP request/response which can be modified by the client or server
short version: meta data about response/request
http-messages-recap
Is a body required for a valid HTTP message?
No, usually the status code is enough
npm-intro
What is NPM?
A package manager for the Node JavaScript platform. Puts modules so that node can find them and manage dependency conflicts
It’s actually 3 things:
- website
- cli
- registry
npm-intro
What is a package?
A package is a file or directory with package.json file in it
npm-intro
How can you create a package.json with npm?
npm init for options or npm init –yes for default package
npm-intro
What is a dependency and how to you add one to a package?
files necessary to run our code
npm install packageName
npm-intro
What happens when you add a dependency to a package with npm?
It’s added to the node_modules directory (makes one if none are found) and adds/updates dependencies property on the package.json file to have that dependency
expresss-intro
How do you add express to your package dependencies?
npm install express,
express-intro
What Express application method starts the server and binds it to a network PORT?
the listen() method.
first you require(‘express’) then do app = express() ‘function’, then app.listen(‘portName’)
Note: require(‘express’) returns a function unlike require(‘fs’) which returns an object
express-hello-world
How do you mount a middleware with an Express application?
the use method of app object
express-hello-world
Which objects does an Express application pass to your middleware to manage the request/response lifecycle of the server?
req (stands for ‘request’) and res (stands for ‘response’) object
express-get-json
What is the appropriate Content-Type header for HTTP messages that contain JSON in their bodies?
Content-Type: application/json; charset=utf-8
Note: worth noting that the headers to be arbitrary, for example it is possible for it to say application/json, but actually be an html file. So headers are just a HINT of what is in the body
express-post-json
What does the express.json() middleware do and when would you need it?
It parses incoming JSON requests and places the data in the req.body (request body).
You’d need it when you’re posting an object
ex: app.use(express.json());
Note: by default node and express don’t show you/take in the body
Notes: command line args are always a string, unless there is a space
express-delete
What is the significance of an HTTP request’s method?
It tells the server what the client is trying to do, but it is up to the programmer to actually decide.
Significance is a communication tool to tell what the client wants to do, but is actually arbitrary
methods are: GET, POST, PUT, DELETE
postgres-intro
What is PostgreSQL and what are some alternative relational databases?
Free, open source Relational Database Management System (RDBMS). Often cited as most advanced open source database of its kind because of its robust feature set, standards compliance, and reliability.
Alternatives: MySQL (also free), SQL Server by Microsoft, and Oracle by Oracle Corporation
Usually toss up between PostgreSQL or MySQL when first learning ‘full stack’
postgres-intro
What are some advantages of learning a relational database?
Once you learn one relational database, then you can learn other relational databases easily because they all use SQL language. Good guarantees about data integrity. They can store and modify data in a way that makes data corruption as unlikely as possible. (devs can make database to reject ‘bad’ data and not worry about ‘half-written’ data- ACID- computer science). Multiple users can access the data and most apps use a database.
Note: relational databases are commonly called ‘SQL databases’ because you usually use SQL language to some degree despite not being PostgreSQL.
postgres-intro
What is one way to see if PostgreSQL is running?
‘sudo service postgresql status’ command in terminal, using ‘top’ command in second terminal, or doing something with it like this command: “ psql -c ‘\l’ “
and if it errors then you know it’s not on
‘pgweb’ is an admin tool/GUI which lets you look at and/or manipulate your database
postgres-database
What is a database schema?
A collection of tables. It defines how the data in a relational database should be organized.
Note: in relational databases, you typically define your schema up front and the database server will make sure that any data being written to the database conforms to that schema
postgres-database
What is a table?
A table (called relations) is a list of rows which have the same set of attributes.
Ex: table could be called ‘students’ which have ‘firstName’, ‘lastName’, and ‘class’ attributes (attributes are referred to as columns).
My interpretation: the table holds the TYPE of data.
postgres-database
What is a row?
A row is a record of something in a table, which has all the same attributes as outlined by the table.
EX: ‘students’ table has ‘name’, ‘class’, ‘dob’ attributes (or columns). This means that each row identifies a specific student.
sql-select
What is SQL and how is it different from languages like JavaScript?
SQL is our primary way for communicating with the database.
SQL is a declarative programming language (like HTML or CSS), meaning you describe the results you want and the programming environment comes up with its own plan for getting those results.
JavaScript is an imperative programming language, meaning you tell JS runtime what to do and how to do it.
sql-select
How do you retrieve specific columns from a database table?
By using the ‘select’ statement followed by the column name in double quotes, followed by a comma if adding more than one, then put ‘from’ statement followed by table name.
Ex:
select “firstName”,
“gradeLevel”
from “students”;
Note: the last clause in an SQL statement has a semicolon at the end
sql-select
How do you filter rows based on some specific criteria?
By using the ‘where’ clause, followed by column name, followed by comparison operators, then if it’s a number just type number or if it’s a string then use single quotes.
Note: it comes after the ‘from’ clause
sql-select
What are the benefits of formatting your SQL?
You should indent SQL code to have a consistent style and therefore better readability.
Note: Reasoning is that it is much easier to read text that is narrower. For example MDN becomes a three column layout when the browser gets big enough and it keeps the text smaller width. (It doesn’t span the whole width of the page).
the select statement and all the clauses like ‘where’ should align to each other, where the ‘e’ in ‘where’ is right below the ‘t’ in ‘select’. Exception is order by where by is lined up with the first quote of column names.
sql-select
What are four comparison operators that can be used in a where clause?
Greater than (>), less than (>), equal (=), and not equal (!=).
Note: you can also use <=, >=, and <>
sql-select
How do you limit the number of rows returned in a result set?
Using the ‘limit’ clause, followed by a number of the max rows you want.
Note: it is the last thing in the code if it is included, unless there is an offset, fetch, or for.
sql-select
How do you retrieve all columns from a database table?
Using an asterisk (*), usually called ‘star’ by devs
sql-select
How do you control the sort order of a result set?
Using the ‘order by’ clause, followed by a column name in double quotes.
BUT it doesn’t actually have to be a column name, it could be order by a value of ‘replacementCost’ for example
Note: default sort order is ascending, but if you put ‘desc’ keyword after the column name then it changes it to descending order.
Note: orders are not predictable, unless ‘order by’ clause is used
sql-insert
How do you add a row to a SQL table?
Using the ‘insert into’ statement, followed by the table name in double quotes, followed by the columns you want to insert in parentheses, followed by the values clause with corresponding to the column names in parenthesis, then lastly an optional returning clause to see what you added.
Ex: insert into "languages" ("name") values ('HTML'), ('CSS'), ('JavaScript') returning *;
sql-insert
What is a tuple?
A list of values
sql-insert
How do you add multiple rows to a SQL table at once?
values clause, then the column attributes in parentheses, then just add a comma at the end.
sql-insert
How do you get back the row being inserted into a table without a separate select statement?
using the ‘returning’ clause followed by the column names you want or just the asterisk
returning * or returning ‘columnName’, ‘columnName’
sql-update
How do you update rows in a database table?
Using the ‘update’ statement followed by the table name in double quotes, Then in the next line use the ‘set’ clause followed by column names in double quotes then an equal sign to what value you want to change it to (commas to separate multiple changes). Lastly include a ‘where’ clause to specify a column name of what you are updating.
Note: can include ‘returning’ clause too
Ex: update "films" set "rating" = 'R', "name" = 'SCARY' where "rating" = 'T' returning *;
sql-update
Why is it important to include a where clause in your update statements?
If you don’t include ‘where’ clause then it’ll update EVERY row in the table
sql-delete
How do you delete rows from a database table?
Using the ‘delete’ statement followed by ‘from’ clause with table name, then using ‘set’ clause followed by assignment operator to value you want, then specifying ‘where’ clause you want to delete (where you can use ‘and’ clause for higher specificity, no comma needed).
Note: can include ‘returning’ clause too
Ex: delete from "films" where "rating" = 'T' and "name" = 'SCARY' returning *;
sql-delete
How do you accidentally delete all rows from a table?
Not specifying with a ‘where’ clause
sql-join
What is a foreign key?
A column that links two tables together based on the column value.
Ex: is ‘filmId’ being in a ‘films’ table AND in an ‘inventory’ table
sql-join
How do you join two SQL tables?
select statement syntax, then using ‘from’ clause for one table, then using ‘join’ clause with second table’s name
Ex: select "firstName", "lastName" from "rentals" join "customers" using ("customerId") join "inventory" using ("inventoryId") join "films" using ("filmId") where "title" = 'Magic Mallrats'
Note: rentals needs to have a ‘customerId’, ‘inventoryId’ needs to be in either rentals or customers table, etc. Basically the previous tables needs to have what you stated in your ‘using’ clause (the foreign key). Putting all joins in one line negates this ordering since going forward/backward doesn’t matter
sql-join
How do you temporarily rename columns or tables in a SQL statement?
By giving them an alias with the ‘as’ keyword. Note this can be done for table names too and that aliases with ‘as’ are temporary (only show in result set, but not actually changed in the database).
Ex:
select "line1", "c"."name" as "cityName", "district", "countries"."name" as "countryName" from "addresses" join "cities" as "c" using ("cityId") join "countries" using ("countryId");
sql-aggregates
What are some examples of aggregate functions?
max(“”), avg(“”), sum(“”), count(“”), min(“”), every(“”), and many more.
Can store JSON in column value (Ex: json_agg() then join actors and castMember table)
sql-aggregates
What is the purpose of a group by clause?
Groups what you’re selecting for into their own rows then applying the aggregate to that, so if you group by “genre” then each row is gonna be like ‘horror’, ‘comedy’, etc.
es6-promises
What are the three states a Promise can be in?
pending (initial state…… then transition to a fulfilled (success), OR rejected (fail)
es6-promises
How do you handle the fulfillment of a Promise?
using then() method of the promise object. It takes two arguments: on fulfilled function and onrejected function. Best to use catch() method for failures.
es6-promises
How do you handle the rejection of a Promise?
Either with the second argument of the then() method or just the catch method which takes an error function as an argument. Best to use catch()
array-filter
What is Array.prototype.filter useful for?
If you wanted to condense an array to certain values. Very useful to filter an array based on a test outlined by a function.
Note: It CREATES a new array of elements that passed the test
Ex: const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
function isPrime(num) { for (let i = 2; num > i; i++) { if (num % i == 0) { return false; } } return num > 1; }
console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13]
array-map
What is Array.prototype.map useful for?
If you want to create a new array containing transformed elements of another array
difference from filter is that it returns same # from original array since it applies change to every single index
for each method is different because it doesn’t return an array (it is undefined by default)
array-reduce
What is Array.prototype.reduce useful for?
Combining the elements of an array into a single value based on the reducer (slash predicate) function
es6-classes
What is “syntactic sugar”?
syntax in a programming language that is designed to make things easier to read or to express
Ex: constructor functions vs classes (same function for the most part, but classes easier syntax)
es6-classes
What is the typeof an ES6 class?
A function (constructor function specifically)
Note: JavaScript classes aren’t real classes (just same as constructor functions for the most part, syntactic sugar)
es6-classes
Describe ES6 class syntax.
- class keyword followed by a class name with a capital first letter
- opening curly braces
- constructor method with some parameters, then assign ‘this’ object to the parameters
- under constructor method make other class methods
Note: ‘this’ will refer to the ‘class’ variable
- To add new object to class then do `let john = new Person("John Doe");` Note: new objects of the class automatically call the constructor() method
NOTE: arrow functions behave differently with classes/constructor since ‘this’ is defined at definition time (double check if it’s call time or definition time)
Use classes/constructors when you want an obj to have behavior (OOP typically for ppl that make frameworks or libraries, so not typical for apps development)
es6-classes
What is “refactoring”?
Restructuring existing code (changing the factoring) without changing it’s output/external behavior
webpack-intro
What is Webpack?
A module bundler (a module is just a file) - Webpack bundles JavaScript files into one. (it rewrites the code and makes it smaller for ‘production’ mode)
Note: difference from commonJS (aka exports/import modules) is that WebPack combines all these files into one JavaScript file (main.js by default) to run in a web browser
Webpack automatically finds your ‘src’ folder then your ‘index.js’ exports then creates a ‘dist’ (short for distribution or end product) dir if it doesn’t exist to make a main.js
webpack-intro
How do you add a devDependency to a package?
npm install --save-dev
packageName
devDependencies are for packages not included in the production build/app
webpack-intro
What is an NPM script?
An npm scripts are a convenient way to bundle common shell commands for your project.
Basically a command you type in your CLI to do something with your application (can be given any name in your package.json scripts section). - can use all cli commands and commands in the bin
webpack-intro
How do you execute Webpack with npm run?
full command: npm run build
Have to:
check if package.json file exists, if not npm init -y
Then install jquery with npm install jquery
- npm install –save-dev webpack
- npm install –save-dev webpack-cli
- Add
"build": "webpack"
into scripts property of package.json file
- build can be named anything“build”: “webpack”,
“watch”: “webpack –watch –mode=development –devtool=source-map”,
devtool gives better errors
mode makes it load faster with dev mode
es6-modules
How are ES Modules different from CommonJS modules?
- Main difference is that they are officially supported by the browser, but commonJS modules aren’t
- Static module structure which means you can determine what to import and export without having to execute the whole file.
- don’t use require() and module.exports statements
- More compact syntax
Note: with import { } we are importing ‘named’ exports, but if we do import someName from ‘./something’ then it’s by default. (default is just a name, so when importing it then you can say import ‘namedWhatever’ rather than import ‘default’)
es6-modules
What kind of modules can Webpack support?
ECMAScript modules CommonJS modules AMD modules Assets (just any file you want to import) WebAssembly modules
Note: It can look at absolute, relative, and module paths
Note: In the exercise, when ‘../lib’ is used then it means it looks for an index.js in the lib directory and the index.js has all the imports instead of doing individual imports in each file like noop.js and to-array.js)
Note: Tim has made dom creation function which can be used to refactor AJAX code. It basically calls the function and makes the DOM
react-elements
What is React?
A front-end JavaScript library (all frameworks are libraries though for conversation) for creating user interfaces
Note:
- libraries (you call their code)
- frameworks (they call your code)
If there is an inversion of control then it’s a framework
- Sample statement = My understanding is that there is an inversion of control, so all frameworks are libraries, but not all libraries are frameworks
react-elements
What is a React element?
They are plain objects that describe what the DOM element should look like.
NOT an HTML or DOM element
react-elements
How do you mount a React element to the DOM?
You import the ReactDOM from the react-dom package, then use ReactDOM.render(elementName, containerName) to mount an element to the page
Note: we dont use dots or slashes to import because it’s a package, not at a path on our computer
Note2: we usually only run ReactDOM.render once, unlike other render functions. It also completely changes the child elements of the specified container (makes React own it). Never touch DOM/ do DOM manipulation if you use React
babel-intro
What is Babel?
Babel is a JavaScript compiler (short answer). It’s a toolchain that is mainly used to convert ES 2015+ (aka ES6) code into backwards compatible version of JavaScript in current/older browsers/environments.
compiler means it translates programming language to another language, in this case new JS to old JS
Note: lets it works on older browsers
babel-intro
What is a Plug-in?
A software component that adds a specific feature to an existing computer program. It’s customization or addons.
babel-intro
What is a Webpack loader?
Loaders are transformations that are applied to the source code of a module. They allow you to processing files as you import or load them into another language.
They are used to customize the features of webpack, in this case we are using babel to make JavaScript code backwards compatible.
Note: don’t need loaders to use webpack
babel-intro
How can you make Babel and Webpack work together?
npm install –save-dev babel-loader
also need to module.exports loader: babel-loader
in webpack.config.js file
react-jsx
What is JSX?
Syntax extension to JavaScript. It is commonly used with React, and it produces React ‘elements’ but with using the syntax of a template language like HTML.
Note: don’t read it like HTML even if it looks like it (can use babel to see what it actually looks like)
Should name files .jsx to get syntax help in VS Code
react-jsx
Why must the React object be imported when authoring JSX in a module?
Have to be sure that React is available because JSX will call for React eventually (it’s actually calling React.createElement even though it looks like HTML
react-jsx
How can you make Webpack and Babel work together to convert JSX into valid JavaScript?
Babel Loader with the plugin transform-react-jsx
react-function-components
What is a React component?
Reusable and independent bits of code, which serve the same purpose as JavaScript functions. They return React elements. Alternatively called ‘function components.’
react-function-components
How do you define a function component in React?
function keyword, variable name, 1 parameter props, then opening curly braces, then return React element
react-function-components
How do you mount a component to the DOM?
create an element variable which calls the component with the desired values. Then use ReactDOM.render(element, container)
first arg of ReactDOM.render NEEDS to be a React element
react-props-and-expressions
What are props in React?
Props are arbitrary inputs, basically parameters for React components
Worth noting they ARE objects (that’s why it is called props)
reacts-props-and-expressions
How do you pass props to a component?
React Component then prop name = some value
- create react component
- key name/prop name
- equal sign then value in a string
Note: can have multiple props, kinda like HTML attributes
react-props-and-expressions
How do you write JavaScript expressions in JSX?
You put it in curly braces
react-class-components
How do you create “class” component in React?
class keyword, followed by variable name starting with capital letter, that extends to the component property of the react method (React.Component), opening curly braces, then a mandatory render() prototype method in the class body which has a return statement for a React element
Ex:
class CustomButton extends React.Component { render() { return {this.props.text}; } }
react-class-components
How do you access props in a class component?
using ‘this’ object
Ex: this.props.propName
react-events-and-state
What is the purpose of state in React?
The purpose of state is to keep track of values that change over time
In this exercise, the state is whether the button was clicked, not the change of text. Think of state as data model, render is where you put styling aka CSS
react-events-and-state
How to you pass an event handler to a React element?
Pass it as a property
react-rendering-lists
What Array method is commonly used to create a list of React elements?
the map() method which applies a change to every single item in the array.
react-rendering-lists
What is the best value to use as a “key” prop when rendering lists?
The best value for a key is the props’ id, if it doesn’t have one then you can use the index, but that isn’t encouraged.
react-form-controls
What are controlled components?
An input form element whose value is controlled by React
- Components that have an internal state which is managed by React, usually refers to native HTML elements.
Note: Totally okay to make multiple 3 different handler functions for 3 inputs like email, name, comment, etc.
Purpose is for when user needs to update a form then it comes prepopulated.
react-form-controls
What two props must you pass to an input for it to be “controlled”?
props: control, value, and listen for, onChange,
express-static
What does express.static() return?
A middleware function (think of it as a barebones server and all you need is a ‘public’ directory for your frontend files/code)
static = serves same thing to every user without modifications dynamic = serves something to a user based on logic of the request
NEED to use path.join to guarantee that node uses the ‘public’ directory next to your index.js (server code)
kinda serves as security too since it gives users access to only the ‘public’ directory
express-static
What is the local __dirname variable in a Node.js module?
the absolute path to the directory of the current module (same as path.dirname() of the __filename)
express-static
What does the join() method of Node’s path module do?
Joins all given path segments together (paths should be strings unless and relative unless __dirname)
Basically concatenates all files together (relatively pathed), but it follows the order of the path, so if you do ‘..’ at the end then it just exits out (see example on node.js)
fetch
What does fetch() return?
A Promise that resolves to a Response object (which is a representation of entire HTTP response)
Note: The first then method() is the only one that’s a PROMISE, javascript will wait until that promise is fulfilled to pass in the parameter into the next then method
Differences from xml http:
Benefit of fetch: then() chaining
Cons: no progress event (so hard to implement loading bar)
fetch
What is the default request method used by fetch()?
GET method
NOTE: res.json() doesn’t return the data, it returns a Promise. of the data
There’s instances where you don’t use res.json(), but it’s rare
fetch
How do you specify the request method (GET, POST, etc.) when calling fetch?
Add a method property in second argument of fetch method.
Ex: method: ‘POST’ // or PUT, DELETE, GET, etc.
fetch-in-react
When does React call a component’s componentDidMount method?
Invoked immediately after a component is mounted (inserted into the tree)
order: constructor called first ONE time, then render method, then after that componentDidMount called ONLY ONE time after first successful render()
fetch-in-react
Name three React.Component lifecycle methods.
componentDidMount(), componentDidUpdate(), and componentWillUnmount()
*all invoked immediately based on their names
render() is also one
fetch-in-react
How do you pass data to a child component?
using props (do this any time you want to share data b/w components)
javascript-closures
What must the return value of ‘myFunction’ be if the follow expression is possible?
myFunction( )( );
myFunction is being called and then it’s being called again on the return of the first call
Note: functions can call other functions, and a function knows when it was defined
javascript-closures
What does this code do?
const wrap = value => ( ) => value;
function wrap (value) { function ( ) { value } }
It defines a function named ‘wrap’ with one parameter, value, which calls an anonymous function with the return value of ‘value’
If you call wrap, you get back a function. The point is to store a variable and then retrieve that value
javascript-closures
In JavaScript, when is a function’s scope determined; when it is called or when it is defined?
When the function is defined (aka lexical), or more accurately when it’s compiled
EVERY function’s scope is at function definition
Note: Good example is clickCounter with an event listener.
Event listener callback has a closure on the ‘counter’ variable outside of the event listener
javascript-closures
What allows JavaScript functions to “remember” values from their surroundings?
Closures
Which is a combination of a function and the lexical environment within which that function was declared.
Note: All JS has access to variables outside of it, but they cant look into functions and access variables
What does the acronym LIFO mean?
last-in-first-out
Refers to stacks where last thing that is ‘pushed’ onto the stack is the first thing that can be popped out.
What methods are available on a Stack data structure?
push(), pop(), peek()
What must you do to access the value at an arbitrary point in a stack (not just the “top”)?
Pop from the stack repeatedly until we see the value we want.
linear time complexity - O(n)
What does the acronym FIFO mean?
First-in-first-out
Relates to queues: the first thing enqueued onto the queue is the first thing that can be dequeued out
What methods are available on a Queue data structure?
Enqueue() - adds value to the ‘back’ of the queue
Dequeue() - removes the ‘front’ value from the queue and returns it
Peek() - returns the ‘front’ value of the queue without removing it
shift and pop for arrays
Not optimal to use arrays because shift() makes JS have to reassign every value.
But if you run into a question where you need to use queues/dequeues then just say that I will be using arrays as a queue. I know it’s not as optimal as a queue though.
What must you do to access the value at an arbitrary point in a queue (not just the “front”)?
Dequeue() repeatedly (n times) until you reach arbitrary point you want
Linear time complexity - O(n)
How are linked lists different from an array?
Linked lists are sequential access (like a queue), not random access (like an array). That means that, in order to go to a specific place in the list, you have to start at the beginning, then jump from node to node until you get there.
random access is ‘constant time’ O(1) no matter how big the array is
Linked lists are not typically used for anything practical for web development
How would you access an arbitrary node in a linked list (not just the “head”)?
you have to start at the beginning, then jump from node to node until you get there.
linear time O(n)
Problems solved with stack, don’t define your own class just use the predefined methods