Random Notes Flashcards
Code reading for html-relative-links:
anchor tag href=”../about-me/about-me.html”
There is an opening tag for the anchor element and there is an href attribute with a value of a relative URL pointing to the about-me.html file within the about-me directory within the parent directory (..).
- The forward slash is read as “within” and we start with the file we are trying to actually read (subject first)
- We call them folders day to day, but it’s really called the directory”
Should you use divs or br to change up the document flow
Use divs to change document flow
br elements should only be used for breaking up text.
Do you need a label element for form control elements?
Not always. If there’s no text labeling the input area then you don’t need labels. You can just use placeholder attribute.
Code reading for CSS-colors
CSS selector { *background-color: rgb(244, 249, 251)}
we have a property with a CSS function, rgb, with the ARGUMENTS (244, 249, 251)
CSS: How background-colors work?
thead tr th tr thead
“Hey dude! Great question, that is because if you apply the styling to thead, the background color you are applying to the tr element will overlay that background color, and it would not be visible”
The child elements overlay the parent elements
CSS: Code reading for pseudo class and descendants and children.
table.striped thead > tr:nth-child(odd)
A new css rule set with a selector for the tr element with a pseudo class (nth-child) with an argument odd which is a direct child of thead and is a descendant of the table element with a class striped.
TIP:
CSS Layout control rules
Container should always be the external layer
Containers only hold rows
Rows should only hold columns
Guide to make classes for HTML and CSS
Utility classes = named after the desired behavior. It’s made to be used multiple times, things that repeat. It should only have one or two things it does. They shouldn’t be changed. Instead make a new class with the desired behavior.
Semantic classes = named after what it’s holding. Add as last attribtute after all the utility classes
Two things container should always have?
Width or max width AND margin: auto;
What is the only thing that should be in the row class?
display: flex;
What are the only things in a column class?
Only width
Position absolute has to be a child of relative.
Most of the time, but not always.
Width:100% or offset properties of top, bottom. right. and left set to a value of 0?
Both work.
Offset values of 0 will make it take all available width.
Primary use of absolute positioning?
If you need to layer something on top of something else.
CSS Layout classes for row, column, and container.
Row = display flex; column= width container = width (with hard px val) and margin auto
JavaScript code reading:
console.log(‘value of:’, typeof fullName);
the log method of the console object is being called with two arguments, the string, value of, and the result of the expression typeof fullName
JavaScript code reading ‘.’ is read how?
How is vehicle[‘color’] = ‘white’ read?
the dot (period symbol) is read as of
the string white is being assigned to the variable vehicle at string color (brackets are read as ‘at’)
Good thing to note about objects and primitive data
var me = {name: "john", age:"20"}; undefined var otherMe = me undefined otherMe.name = 'chad' 'chad' me {name: 'chad', age: '20'} var a = 1 undefined var b = a undefined var a = 12 undefined a 12 b 1
Square brackets [ ] =
Curly brace { } =
square is for array literal
curly brace is for object literal
Data Modeling, think about data what you need and how to store it
It’s best to create a diagram or something to plan out the data.
What is a javascript expression?
Chunk of code that is being evaluated and returning a value
JavaScript code reading:
function convertMinutes(minutes) { var seconds = minutes * 60; return seconds; }
var convertMinutes = convertMinute(5);
a function is being defined with the name convertMinutes with one parameter named ‘minute’
the value of minutes is being multiplied by the number 60 and the result of that expression is being assigned to the variable seconds
the variable seconds is being returned FROM the function.
the function convertMinutes is being called with one argument, the number 5, the return of that function call is being assigned to var convertMinutes
CSS E-commerce challenge (due Monday, probably can be done by Friday)
strikethrough element? s
background color on current price
LV picture is a different sized picture on purpose (challenge)
object-fit (css property) - useful to adjust height/width without messing up aspect ration on images
How to read:
var something = math.floor(randomValues)
var firstBook = library.shift();
the floor method of the math object is being called with one argument, the variable randomValues and the return of that method is being assigned to the variable something
the shift method of the library object is being called with no arguments and the return of that method is being assigned to the variable firstBook
JavaScript If Code reading:
function isUnderFive(number) { if (number > 5) { return true; } else { return false; }
there is a function being defined with the name isUnderFive, with one parameter NAMED ‘number’ and then the opening curly brace for the function code block. We have an if statement with the condition ,variable number is greater than 5. then opening curly brace for the if statement.
the boolean value true is being returned from the function
the boolean true is being returned from the function
closing curly brace for the if statement,
Note that from “if” to the closing curly brace is the “conditional”
JavaScript for loops code reading: for (var i = 0; i < string.length; i++)
for (var key in object) {
keys.push(key)
}
return key;
for loop with an initialization of the number 0 being assigned to the variable i, a condition of i being less than the length property of the string object, and a final expression of the variable i being incremented by 1
for in loop with the var key in object, object then opening
push method of the keys object is being called with one argument the value of variable key
value of the variable key being returned from the function
@media rule code reading
@media only screen and (min-width: 768px) { .card-wrapper { flex-basis: 50%; } }
There is a new @media rule for only media type screen and a media feature of min-width: with a value of 768px followed by the opening curly brace for the @media rule set. Then read as normal
*Note: min-width in the @media rule is not a property, it is a media feature
Template literal code reading
const hello = `Hi my name is ${firstName}
There is a template literal with (just say the string as if reading) with a javascript expression, with the value of the variable firstName, and the result of that expression is being assigned to variable const hello.
es6-destructuring code reading
const { title, author, libraryID } = book1;
const [book3, book4, book5] = library;
const [, , , book6] = library;
// if it's an array you say 1st, 2nd, 3rd element is being destructured // if it's an object you say properties names // third option just say it's the 4th element // Code Reading for destructuring: // 1. What is being destructured // 2. Where is it being destructured from // 3. Where is it being assigned to
Library vs framework
Answer is that all libraries are frameworks, but not all frameworks are libraries. Frameworks have inversion of control
all libraries are frameworks, but not all frameworks are libraries (called inversion of control - who calls who)
- Using framework if you define functions, but never call them (some exceptions) instead hand them over it means your library is a framework (DOM is a framework for the events)
- If library has a bunch of functions and methods, and your code calls it then it is just a library
Gray area exists (meaning it could be more library-heavy or library-light).
Node.js is a runtime environment that comes with a library
If you convert an object into a string, what does it return
it returns object Object
node-require example answers
subtract function which is exported
function subtract (x, y) { return x - y; }
module.exports = subtract
node-require code reading
const add = require(‘./add’);
console.log(‘result:’, add(x, y));
the require function is being called with one argument, a string, and the return of that function is being assigned to the variable const add
the log method of the console object is being called with 2 arguments, a string and the RETURN of the function add with two arguments, x and y
four major concepts of JavaScript
- prototypal inheritance
- how ‘this’ works
- closures
- the event loop
node-require example answer for calculate.js
assigned process.argv[2] and process.argv[4] are assigned to a variable which is called in the functions
Used parseFloat to have decimals instead of parseInt which is just an integer, but using Number() method might be better
so ex: const x = parseFloat(process.argv[2]) const operation = process.argv[3] --- this stands for the middle word like 'plus' or 'minus' const y = parseFloat(process.argv[4])
add(x, y)
node-fs-readfile sample answer
read-any.js
// Enable interaction with the file system const fs = require('fs');
// Assigning user input into a variable const filename = process.argv[2];
// asynchronously reading the contents of the file // and encoding it using the utf8 character set fs.readFile(filename, 'utf8', (err, text) => { // Check if there was an error while reading the file if (err) { // if there is an error console.error(err); // write the error to the process's stderr process.exit(1); // forcibly quit with a failure code (not 0) } console.log(text); // otherwise print the file content to stdout });
node-fs-readfile: When not using ‘utf8’ = Buffer terminology
binary: 0 or 1 -> base 2
bit: binary integer (literally just represents binary)
byte: 8 bits
decimal: 0, 1, 2, 3, 4, ,5, 6, 7, 8, 9 -> base 10
number base: how many different digits/ characters you have available to represent numbers
hexadecimal: a-f, 0-9 -> base 16
- Without ‘utf8’ in readfile method then the text is raw bytes data which is converted into hexadecimal data*
ex: 6d = ‘m’ = m.toString(2) will show binary code
http-messages-recap
content-type
Responsible for how the data is shown/displayed
npm-intro
packages have packages.json files
packages.json is not a package, it’s just a file
npm-intro
Rules before installing packages
- check if the GitHub link works so ou can review if code is sketchy
- Proper documentation
- Popularity - is it frequently used? (check weekly downloads)
DISCLAIMER: anyone can publish packages on npm
express-get-json
app.METHOD is the same as what?
It is the same as an add event listener, which means app.METHOD is called once, but its callback arrow function is called numerous times when the METHOD is called.
express-post-json
app.post ex:
const jsonMiddleware =express.json()
app.post('/api/grades' function (req, res) { // grab request body const newGrade = req.body // get current 'nextId' value and increment it for next time const id = nextId++ // take current id and assign to new grade var newGrade.id = id // store complete new grade in data model grades[id] = newGrade // respond to client with the obj we stored and a created status code res.status(201).json(newGrade) }
nextId = 1 // don't need to adopt this style of incrementing, not needed Notess: const id = nextId
using id var is current value so 1
But if you call id after then it uses value 2
express-post-json
method chain code reading
res.status(201).json(newGrades)
the status method of res obj being called with 1 argument, then the json method of the return of the status method being called with 1 argument newGrades
It so happens that res.status(201) returns res obj
similar to string.toUpperCase().split()
express-json
Does the route lead to folder or file?
No it doesn’t have to, it is just telling the server the route to access.
Full Stack Developer = 3 Tier Architecture
Casual term vs professional term
Back end = Web/HTTP Servers
Front end = Browsers/Client software
Databases = DBA (Database Administration)
Note: LFZ learning breakdown (30% backend, 60% frontend, 10% databases). Most likely end up getting a job in front end because we learn enough back end to become a better front end developer. Can still get a job in back end, but prob not full stack.
Only learning how to use database, what a database is, and how to integrate it into your app.
More Full stack
Full-stack
- Client (browser)
- Server (node.js / express)
- Database (PostgresSQL)
- client sends request to the Web Server (request)
- Server receives the request (request)
- Server sends a query to the database (INSERT a new row)
- Database replies to the server with a ‘result’
- Server can now send a response to the client
Note: Client and Server are RELATIONSHIPS (not things)
- The ‘server’ is a ‘client’ of the database.
PostgreSQL documentation reading tip
brackets [ ] means it is optional
curly braces { } means you have to pick one
parenthesis ( ) means you have to have them if you choose that option
pgweb query tab
You can use the explain query/analzye query by the run query button to see query logic
PostgreSQL backup
In terminal, pg_dump pagila > pagila.backup.sql
pagila is just the sample db name
PostgreSQL transactions
should always use psql dbName to enter env in terminal????
commands:
‘begin;’ starts a transaction - it lets you do any statement without client seeing till you’re finished (think of it as a branch)
can use ‘rollback;’ to undo transaction
or ‘commit;’ to make changes for everyone
just use ‘begin;’ on its own line
don’t use pgweb to manipulate data
use cases for join clause
for favorites
With statement postgresql
with "actorFIrstName" as ( select 'firstName' as 'name' from 'actors' ), 'actorLastName'. as ( select 'lastname' from 'actors ) select 'name', 'surname' from 'actorFirstName' join 'actorLastName using('actorId') limit 5
can use subqueries too (select statements inside ‘from’ clause)
es6-promise differentiation from fs.readfile callback
promise guaranteed to run error and then callback ONCE, but readfile can have bugs by devs which cause the callback to get called twice.
promises takes away ‘callback hell’
filter function
It’s a synchronous function so the ‘callback’ parameter is really a ‘predicate’ since it’s called on the stack right away
Note: It substitutes for loops
actually slower than regular function with loops and conditionals because filter placed on stack, THEN predicate is placed on and off stack over and over till end of array.
May be useful for search engines/bars
Research passed by reference (immutability), this affects arrays and objects
array1 = array2, makes it so array1 === array2
const array2 = array1.slice(), makes it so array2 is a ‘shallow copy’
obj1 = obj2, is ===
for shallow copy of object use ‘Object.assign({}, obj1)’
reduce function tips for naming parameter
name ‘previous’ parameter to what the return value would be identified as, so like ‘balance’ for bank accounts
name ‘currentVal’ parameter to what the thing in your input array is, so ex: is transaction for an array of transactions
Note: can recreate map and filter with reduce method… reduce is the most general and most powerful
Useful array methods Tim uses other than map, filter and reduce
find(), forEach(), reduceRight(), every() (REALLY GOOD - checks if everything in array has predicate func return to true), some()
es6-classes
code reading classes
class Student { constructor(firstName, lastName, subject) { this.firstName = firstName; this.lastName = lastName; this.subject = subject; }
getFullName() {
return ${this.firstName} ${this.lastName}
;
}
getIntroduction() { const fullName = this.getFullName(); return `Hello, my name is ${fullName} and I am studying ${this.subject}.`; } }
new class definition named student with the opening brace for the class body
Each function lookalike is actually a prototype method being defined named ‘constructor’ with 3 parameters
Visualization of classes/constructors
function createStudent() { return { fullname: function getFullName() {}, introduction: function getIntroduction() {} }; }
Check out MollyRocket on youtube
https://www.youtube.com/watch?v=Ge3aKEmZcqY
react-jsx
code-reading
const element = <h1>Hello, JSX!</h1>;
ReactDOM.render(
element,
document.querySelector(‘#root’)
);
creating react element of TYPE, h1, with CHILDREN, ‘hello, jsx’, and the result of the expression is being assigned to the const variable element
the render method of the ReactDOM obj being called with 2 arguments: the value of the variable element and the return of the querySelector method of the doc object being called with one argument, string hashtag roo
Note: angled brackets means it is a react element
react-props-and-expressions
code reading:
import React from ‘react’;
import ReactDOM from ‘react-dom’;
function CustomButton(props) { return ( {props.text} ); }
const element = ( <div>
</div>
);
ReactDOM.render(
element,
document.querySelector(‘#root’)
);
- Importing react from the react package
- Importing reactDOM from the react-dom package
- There’s a function being defined named Custom Button with one parameter, props, opening curly brace
- The result of an expression is being returned from the function with 1 argument, the React Element of type button with children, the result of the JSX expression, text property of the props obj,
- The render method of the ReactDOM object is being called with two arguments, the variable element, and the return of the queryselector method of the document obj being called with 1 argument, the string #root
Setting up React environment
npm installs:
Dependencies 1. npm init -y 2. npm install react react-dom Dev Dependencies: 3. npm install --save-dev webpack webpack-cli babel-loader @babel/core @babel/plugin-transform-react-jsx
npm scripts:
- “build”: “webpack”,
- “watch”: “webpack –watch –mode=development –devtool=source-map”,
files: mkdir src mkdir dist touch dist/index.html (Make div#root and link script with src="main.js") touch src/index.jsx touch webpack.config.js
paste into webpack.config.js:
module.exports = {
resolve: {
extensions: [‘.js’, ‘.jsx’]
},
module: {
rules: [
{
test: /.jsx?$/,
use: {
loader: ‘babel-loader’,
options: {
plugins: [
‘@babel/plugin-transform-react-jsx’
]
}
}
}
]
},
performance: {
hints: false
}
};
Use npm run build to load page once
Use npm run watch to have continuous reloads on save (along with live server)
react-events-and-state solution w/ explanation
import React from 'react'; import ReactDOM from 'react-dom'; class CustomButton extends React.Component { // FIRST instantiate a CustomButton object from this class - ONE TIME constructor(props) { super(props); this.state = { isClicked: false // establish an initial state }; this.handleClick = this.handleClick.bind(this); // create a bound copy of the prototype method handleClick // assign the bound copy to an "own" property of this object // with a permanent "this" to guarantee the value of "this" when it's called } handleClick(event) { // ONLY decide how to update state by calculating a new state event.target.className = 'tim will kill you'; // NO, you're fired. // Tell React which state propert(y|ies) to replace this.setState({ isClicked: true }); // please transition to a new state // schedules a re-render with a new state (render will be called again) // Add a toggle version... } // 2. React _immediately_ calls the render method after the constructor // Will re-run when this.setState() is called in the future render() { // ONLY decide how the UI should look /** * DON'T * - manipulate the DOM * - update global variables * - use timers */ if (this.state.isClicked) { return Thanks!; // add an onClick prop for toggling if desired /** * { * type: 'button', * props: { * children: 'Thanks!' * } * } */ } return {this.props.text}; /** * { * type: 'button', * props: { * onClick: this.handleClick, * children: 'Click Me!' * } * } */ } } ReactDOM.render( , document.querySelector('#root')
General strat for react even listeners
General strat for event listeners:
- Decide how to update state, most likely don’t have loops, it’s mainly conditionals
- IE don’t use it to manipulate the DOM, React owns the DOM
General strat for render:
- Decide how the UI should look
How to get auto updating node.js server
npm install –save-dev nodemon
“scripts”: {
“dev:server”: “nodemon index.js”
}
npm run dev:server (to keep server on)
Command line tips
touch src/{index, hot-button}.jsx - adds multiple files (2)
command ‘tree’ directoryName shows tree of folder
React website building (hot-button)
- define component
- make render() first and just print something to page (don’t make constructor and handlers first)
- Now make constructor to establish state for the component
tip: use react dev tools instead of console.log bcuz async so might console.log wrong place and receive false data. - define css classes for the different button colors, but don’t add styling
- set up render logic, naive way = if/else statements, and add classNames
tip: turn off autosave in VS Code and have terminal to see build output by webpack and have browser visible for live reload too
Another tip: you can click on react dev tools to change state/props manually so like 4 clicks instead of 0
Tip: It is smart to mock DOM in HTML, but it’s better to just start mock up in render method of the component. that way you’re using react more - Add CSS styling
Note: we haven’t added in event listeners yet, it’s more important to do the mockup THEN add behavior aka clicks later - Start adding handler functions. (logic: console.log() something to make sure click is registered, add variable that reads the current state, add variable that calculates new state, and then replace current state) with this.setState - DON’T change original values with push() or ++. Event listeners should never return something explicitly.
- bind event handler functions
- Test functionality
- to solve naive way: identify what’s different about each one, in this case it’s just className.
- You can just add if/else before the return statement, so make a className var and only have to write one react element (viable for 1-3 things that are different)
- Better way if changing a lot of stuff like this then make a function outside the render method then add our function with a JavaScript expression.
How to describe in interview:
- when program starts we mount the component aka HotButton
- in that component we test this condition
- then render the react element based on that info
Important note: don’t need handler function logic to test functionality, you can update state manually with reactDevTools or constructor state.
Big NOTE: check code often and do everything in steps, shouldn’t have 50 lines of codes and page doesn’t run
Limited breakdown of static middleware
function createStaticMiddleware(directoryPath) { return (req, res, next) => { const filePath = req.url; // ex: styles.css const absoluteFilePath = path.join(directoryPath, filePath); fs.readFile(absoluteFilePath, 'utf8', (err, fileContent) => { if (err) { next(err); } else { res.send(fileContent); } }
ternary expression reading
ternary expression with the condition this.state.isLoading, if truthy the result is a react element of type p with child text loading… and if falsy reactelement userlist with props users with a value of a javascript expressioon
result of the ternary expression being returned from the render function
note 3 types: binary (+ = - >), unary (++ – !), and ternary (3 things: condition, truthy, or falsy)
Interview question for react job
Do you know the react component life cycle?
Basic answer:
1. constructor needs to run ONCE for entire life cycle of component
2. then render()
*look up virtual dom vs real dom (probably another question)
- then componentDidMount() if it is defined (called on first successful render)
- then time passes, if setState is eventually called then it triggers a re-render which runs the render method again
- ComponentDidUpdate() will be called after every subsequent render from first
- ComponentWillUnmount
Basically asks when these things are called.
lifting state up brief explanation
share data b/w two components that aren’t parent/child
pass state as a prop
‘throw’ keyword
It throws EVERYTHING off the call stack.
In the case of express it throws then the express middleware catches it and handles the error based on default or if custom error function deifned
Meanings of json() in different techs
.json() ::::
- express.json() create a json-parsing middleware (server) - res.json() in Express responses - send a JSON response (server) - res.json() in fetch responses - download and parse a JSON repsonse (client)
argon2
.verify(hashedPassword, providedPassword)
verify returns a promise for the password if the arguments match (a boolean), after that we can access the hashedPassword with:
.then (result => {})result is the hashedPassword we receive from .verify()
so the then() method’s arrow function parameter, after a ‘promise’, should be whatever the data is returned by the promise
payload and jwt.sign (json web tokens)
payload is anything that can be turned into JSON so objects and arrays and is turned into base 64 token with .sign()
TOKEN_SECRET (the signature) is a ‘password’ for the server to verify the password - basically encryption of ORIGINAL payload
- each login gives a new token
- token is used to identify the user
resource link: https://jwt.io/#:~:text=the%20client%20side.-,Algorithm
what does import ‘dotenv/config’ do?
it pulls all the key/value pairs from the .env file and makes it a property on the process.env object. That way you can use process.env.EXAMPLE to access that key name/value
having .env.example means people can easily clone your repo
It also lets us deploy our project on a server easily without using variables/parameters specific to your local pc
How middleware works
This example is related to api-authorization: it is why the function authorizationMiddleware can reassign req.user to payload and we can use that assignment in the app.post in index.js
Middleware pokes into the req, res, etc. of the http request
It goes in order from top down, so it matters when app.use(someMiddleware)
how to look at destructuring
const { name } = person.name???
const person = { name: hello }
const name = person.name
how to find props in react?
Go to current class name then right click and find by ‘reference’
React special props: ref, key
index.js for react-file-uploads
purpose of ref is a way to poke a hole through to the real DOM since React is fully in charge of dom.
It sticks a reference of the REAL DOM element so that you can use and access DOM info just like vanilla JavaScript (Tim said it’s used for handing over DOM elements to another library.)
In this case we are using it to access the files property of image inputs so that we can get the actual file of the upload (the event.target.value isn’t enough info)
It’s a case of React’s virtual DOM and the REAL DOM
Another example: In a chat app you’d need a ref for the div box of the chat and access the scrollTop of the DOM element, which React can’t do.
Note: database isn’t storing the image itself, it’s storing the location of the image
TO style file inputs (NVM)
Maybe hide the actual fileee
DbDesigner (typed with camel case)
IT DOESN’T autosave
- new project
- create table
- name table based on main topic
- add field (‘text’ for strings and don’t allow ‘null’ for photos)
- photoId = serial (unique identifier w/ primary key and auto increment) Put ID on top of table
- uploadedAt = timestamp with time zone (nothing checked)
- foreign key means it’s a reference to another table (ref to table and ref to specific column - draws an arrow) - foreign key should be integer
- unique key for usernames (don’t mark as unique, just use text, for hashedPasswords)
- ‘point’ type is for storing latitude
- ‘allow null’ means form isn’t required
- don’t ask for email if not needed
Tip: usually an object (data model) means it’s a table - serial is for the column that identifies the table
- Attaching photoId and userId in likes table checks for if someone liked a specific photo (don’t autoincrement foreign keys)
- when done ‘export’ with create script (warning BUG- it should be “public” . “photos”, NOT “public.photos”) - PASTE this below ‘create schema “public”; in the schema.sql
- if error or want to add to database, then you should edit in dbdesigner and then export and repaste that into schema file (NOTE: it will delete all existing data)
use db:import and then ‘dev’ script