# SEIR 306 Unit 1 TL;DC <br> (Too Long; Didn't Code)
##### This will serve as a permanent repository for the basic summations of each concept as we teach it, either by day or by lesson.
### Monday, March 6
First day of class! Mostly went over installfest, so not as much today. Make sure everything is installed correctly, it is a bit of a pain but you'll be set up for the rest of the unit, as well as your future coding career.
**Important bash commands:**
`cd <DIRECTORY NAME>`: short for change directory. It will move your location in your terminal to the directory indicated.
`ls`: short for list. will display the files contained inside of your current working directory.
`pwd`: short for print working directory. will display your current directory.
`touch <FILE_NAME>`: will create a file inside your working directory with the provided name.
`mkdir <DIRECTORY_NAME>`: short for make directory. Will make a directory at in your current working directory.
`grep "STRING_HERE" file.txt`: will search for specified string within a given file
`cat file.txt`: will read the given file, and output any text to the terminal.
### Tuesday, March 7
#### Steps to submit a deliverable
In the top level of the deliverable directory run the following:
* `git status` - inspect the output to see what files need to be added
* `git add .` - adds all untracked files in the current directory
* `git status` - inspect the output to ensure that you have staged all the files you would like to commit
* `git commit -m "your commit message here"` - commit your staged files with a message describing what and why your are committing
* `git push origin main` - `push` (upload) all commited files to github
Once you have pushed your files to github navigate to _your fork_ of the assignment repo, you can verify that you are viewing your fock because the repo name is prefixed with your github username:

Navigate to the `pull requests` tab and click on `New pull request`


When making a new pull request check the `head repository` (where you are going) and `base repository` (where you are coming from). The `head repository` should be the assignment from the `WDI-SEA` or that you forked, and the `base repository` should be your fork.

Make sure that you fill out the title (required to make a new pr) and the pull request template, once done clikc `Create pull request`

You will be take to a screen that looks like this, indicating to have successfully created a pr:

**HTML**
Short for Hypertext Markup Language. You should think of it as the structure of our documents. To liken it to a house, its the actual base house itself.
A typical HTML tag looks like this:
```htmlmixed
<p>Content</p>
```
All HTML tags have an opening tag, and SOME HTML tags have a closing tag, like this paragraph tag.
HTML elements can be nested within one another. If an element is within another element, it is referred to as a *child* element, and the one it is inside of is the *parent* element.
```htmlmixed
<div class="parent">
<p class="child">Content</p>
</div>
```
Here is the usual HTML boilerplate, which should automatically happen if you type `!` at the beginning of an HTML file:
```htmlmixed!
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>
```
**CSS**
Short of Cascading Style Sheet. So called because the more specific a rule is, that one will take precedence, so it cascades down from general to specific. This is the styling/aesthetic part of your site. Back to the house example, it's the paint, where you put your furniture, etc.
CSS is made up of two parts: selectors and rules. A CSS selector is usually either a class, an id, or an element type, AKA something you can SELECT certain HTML elements by. The second part is the rule. There are many many CSS rules, but some common ones we went over in class are `background-color`, `margin`, and `border`. These define the properties of the different aesthetic aspects of an element.
```css!
#useHashtagsToSelectAnId {
font-size: 16px;
color: red;
}
.usePeriodsToSelectAClass {
background-color: hotpink;
}
h1 { /* here is an example of selecting by HTML element type, like an h1 */
margin: 0 auto;
}
```
**Flexbox**
Flexbox is a layout mode that is widely implemented across different browsers. It super streamlines being able to position things on your webpage based on a set flexbox-defined structure. In order to utilize flexbox, you've got to set the `display` property of something to the value of `flex` in CSS, like so:
```css!
body {
min-height: 100vh;
margin: 0 auto;
display: flex; /* right here! */
justify-content: center;
align-items: center;
}
```
You can find what is generally considered the ultimate guide to flexbox [HERE](https://css-tricks.com/snippets/css/a-guide-to-flexbox/), on a super fun website called csstricks.com.
### Wednesday, March 8
#### JS Review Crashcourse
Javascript varaibles are defined with the keywords `let` and `const`. Avoid using `var`:
```javascript!
let myVar = "hello"
myVar = 10 // varaibles declared with let can be re assigned
const myConst = "some value"
myConst = "something else" // OOPS! JS will throw an error if you reassign a constant varable
```
Javascript has two important classes of datatypes: `Primitives` and `Reference Types`
Primitives are simple, single value types.
```javascript!
// letters and words are a string primitive
"a"
"b"
'c'
"Hello, Strings"
// Numbers are whole integers or floats (decimals)
1
10
3.1415
NaN // not a number
// booleans are logical types
true
false
null
undefined
```
Reference types are data containers:
```javascript!
// an Array is a numerically indexed list of items, starting at 0
const instructors = ["Weston", "Gabe", "April"]
// access 'array elements' with bracket notation
instructors[0] // Weston
istructors[1] // Gabe
// Objects are key/value pair stores:
const myObj = {
fruit: "banana",
number: 10
}
// dot notation is used on objects
myObj.fruit // banana
```
Javascript types have 'methods' that can be 'invoked' to do different things with the data values. More info can be gotten by googling 'Js strin methods' or 'javascript array methods' for example.
```javascript!
let myString = "hello"
myString.toUpperCase() // HELLO
const fruits = ["long pen", "apple pineapple"]
fruits.push("pen pineapple app pen")
fruits // ["long pen", "apple pineapple", "pen pineapple app pen"]
```
Operators let you perform varaious operations with data in js. Check the [gitbook's](https://gasei.gitbook.io/sei/javascript/js-control-flow/02boolean#operator-round-up-for-reference) reference for a list of most all of them.
Watch out for 'type coersion' in JS, sometimes the operators will make assumptions about the types involed:
```javascript!
10 - '5' // 5
10 + '5' // '105'
```
**Boolean Expressions**
Lots of these you've seen before, so let's just review the weird ones:
Bang (!): A reversal of the truth value of some data. Can be verbally expressed as "NOT" something.
```javascript!
!true //false, or "NOT true"
5 != 6 // true, or "5 is NOT equal to 6"
```
And (&&): returns `true` if both statements to the left and right of the && are true. Returns `false` if either statement is false.
```javascript!
true && true // true
true && false // false
```
Or ( | | ): Returns `true` if AT LEAST one statement is true. Returns `false` if both statements are false.
```javascript!
true || false // true
false || false // false
```
Ternary: Essentially a shortened if/else statement. Provide a value to check truthiness/falsiness of, and define code to be ran if it is true or false, respectively.
```javascript!
let age = 20
// conditionToCheck ? codeToRunIfTrue : codeToRunIfFalse
age > 18 ? console.log("You can vote") : console.log("You cannot vote")
// expected output: "You can vote"
```
**Conditional Statements**
#### if/else + else if
You can execute code if a condition is true with `if (condition)`. You can have it execute otherwise with an `else` statment. When you want to provide more conditions to check for truthiness, chain `else if` after your initial code block for the if statement.
```javascript!
let course = "sei";
if (course === "uxdi") {
console.log("Hello, User Experience Designer!");
} else if (course === "fewd") {
console.log("Hello, Front-End Developer");
} else if (course === "sei") {
console.log("Hello, Immersed Developer")
} else {
console.log("Who are you?")
}
// expected output: "Hello, Immersed Developer"
```
#### switch
You can provide a variable to test different values that variable might have, and execute code if that specific case is true.
```javascript!
let grade = "B";
switch(grade) {
case "A":
console.log('You got an A! Great job!');
break;
case "B":
console.log('You got a B! Good job!');
break;
default:
console.log('Try again next time!');
break;
}
// expected output: "You got a B! Good job!"
```
#### Truthiness
Don't forget, all data is either technically "truthy" or "falsy". The falsy values in javascript are `undefined`, `null`, `NaN`, 0, "" (empty string),`false`, and any incorrect math. Everything else will have a hidden value of true when performing logical operators. For example:
```javascript!
let emptyString = ""
let zero = 0
if (emptyString || zero) {
console.log("This code will never run!")
} else {
console.log("false")
}
// expected output: "false", since both emptyString and zero are false.
```
**Loops**
#### while loop
Runs as long as the specified condition is true. MAKE SURE TO HAVE SOME BUILT IN WAY TO MAKE THE CONDITION NOT TRUE.
```javascript!
while (CONDITION) {
// CODE
}
```
#### for loop
This one can be complicated at first, but once you get it, it's an invaluable tool. Most useful when you know exactly how many times you're iterating.
```javascript!
for (ITERATOR DECLARATION; CONDITION; UPDATE) {
// CODE
}
for (let i = 0; i < 5; i++) {
console.log(i);
}
```
#### for of/for in loop
These are similar. `for of`is good for iterating through arrays and `for in` is good for iterating through objects.
```javascript!
for (let ELEMENT of ARRAY) {
// code
}
for (let ELEMENT in OBJECT) {
// code
}
```
### Thursday, March 9
#### Functions
A function is a block of code that can be executed (called 'invoking') at any time in your code.
```javascript!
let FUNCTIONNAME = function(PARAMETER) {
// console.log(PARAMETER)
// expected output: whatever PARAMETER is defined as when invoking FUNCTIONNAME
}
```
Note that parameters are read and given value in the order they're defined in.
```javascript!
let FUNCTIONNAME = function(PARAMETER1, PARAMETER2) {
console.log(`${PARAMETER1}, ${PARAMETER2}`)
}
FUNCTIONNAME('Yo', 'Yeet')
// expected output: 'Yo, Yeet'
```
#### The DOM
Short for Document Object Model. It's a representation of the web page that can be manipulated with javascript to enact change on the web page.
**Selecting DOM Elements**
You can select DOM elements 2 ways, `getElement` and `querySelector`:
```javascript!
let div1 = document.GetElementById("div1")
let div2 = document.GetElementsByClassName("div2")
let div3 = document.querySelector("#div3")
let allDivs = document.querySelectorAll("div")
// since queryselectors can select either classes or id's, you must preface the id/class name with a . for classes or a # for id's. To select by HTML element type, just put the type in as a string, as shown by the last example.
```
**Manipulating DOM Elements**
There are many properties DOM elements have that can changed, way too many for a TL;DC. Here are some major ones:
* `.style`is used to change CSS rules
* `.innerText` sets the text value of an element
* `.className` and `.classList` adjust the class name and list of classes an element has.
**DOM Events**
Literally ANY kind of web page interaction has an associated event (even just loading a page).
This can be used to fire off specific bits of code (AKA functions) when a desired DOM event takes place.
This is most commonly achieved by adding an `eventListener` to an element. An `eventListener` waits for a specific event to occur to a specific DOM element, and then fires off code.
```javascript!
// anatomy of adding an eventListener:
DOM_ELEMENT.addEventListener(EVENT, FUNCTION)
let button = document.querySelector("#button")
let sayHello = function() {
console.log("hello")
}
button.addEventListener("click", sayHello)
// expected output when button is clicked: 'hello'
```
It is generally better to invoke a callback function in an `eventListener` instead of simply writing the code you want to execute (which is doable), because you can only REMOVE an `eventListener` if a callback function is referenced when using `addEventListener`.
```javascript!
// continuing example from above code block
button.removeEventListener("click", function() {
console.log("hello")
})
// WON'T WORK!
button.removeEventListener("click", sayHello)
// Will work!
```
### Friday, March 10
#### Callbacks
A callback function is simply a function that, instead of being invoked by itself, is invoked by another function or method.
```javascript!
let callbackFunction = function() {
console.log("hello")
}
let invokesCallback = function(parameter) {
parameter()
}
invokesCallback(callbackFunction)
// expected output: the invocation of callbackFunction, AKA console.log("hello").
// the only thing invokesCallback does is invoke whatever is supplied as a parameter. Here, we set our first function, callbackFunction, as the parameter.
```
**Timers**
Timers are a good and useful example of functions that take callback functions.
`setTimeout` runs a callback function after a specified amount of milliseconds.
```javascript!
const alarm = () => {
console.log("Wake up!");
}
setTimeout(alarm, 10000)
// expected output after 10 seconds: "Wake up!"
```
`setInterval` runs a callback function constantly after every interval of a specified amount of milliseconds.
```javascript!
const = annoy => () {
console.log('Are we there yet?');
}
setInterval(annoy, 1000);
// expected output every second: 'Are we there yet?'
```
Both functions are removed by `clearTimeout` and `clearInterval` respectively, where the parameter is the callback function you invoked.
```javascript!
clearTimeout(alarm)
clearInterval(annoy)
// kills the interval and timeout from previous code block
```
### Monday, March 13
**Iterators**
#### forEach
A common replacement for the classic `for` loop.
```javascript!
THING_TO_LOOP_OVER.forEach((INDIVIDUAL_ELEMENT) => {
// code to execute for each iteration
})
let numbers = [1,2,3,4,5]
numbers.forEach((number) => {
console.log(number)
})
// expected output:
// 1
// 2
// 3
// 4
// 5
```
#### map
Once a student says `map` stands for Makes Arrays Pleasant and it's very true. Don't forget that `map` RETURNS a new array, it doesn't mutate the old one. This means you must bind your `map`to a new variable.
```javascript!
let numbers = [1,2,3,4,5]
let doubledNumbers = numbers.map((number) => {
return number * 2
})
// expected output:
// 2
// 4
// 6
// 8
// 10
```
#### filter
returns a subset of an array based on whether or not an element meets a condition. This means your condition must return `true` or `false`.
```javascript!
let numbers = [1,2,3,4,5]
// we're gonna abstract out our condition into a callback function this time, for brevity's sake.
let isEven = function(number) {
return number % 2 === 0
}
let evenNumbers = numbers.filter(isEven)
// expected output: [2, 4], since the only numbers whose remainder is 0 after % 2 is 2 and 4.
```
#### reduce
Bit wonky. Basically condenses all values in a container into a single value, based on a certain condition (like addition or multiplication)
```javascript!
const numbers = [1,2,3,4,5]
// as in filter, we will abstract out our callback.
const add = (total, new) => {
return total + new;
}
const sum = nums.reduce(add)
console.log(sum)
// Should output:
// 1 + 2 + 3 + 4 + 5, AKA 15.
```
### Tuesday, March 14
Happy Pi day!
**The Internet and how it works**
The internet is awesome and works because magic. The end.
**AJAX**
AJAX is not an actual function or method or anything, but rather refers to a series of techniques that allow for, as the acronym implies, Asynchronous Javascript And XML.
There are many implementations of AJAX, but the most out-of-the-box ready to use is `fetch`.
Sometimes our code needs to wait for something to finish running before something else can run. This is what's known as *asynchonous* code. For example, pulling something front the internet like data about movies or pictures of cats takes longer than reading and executing our javascript file, for example. But we NEED those cat pictures before our javascript can work right, so we need to wait for the cat pictures, and THEN our code can run.
#### Promises
This is where promises come into play. A promise is basically your code saying that as soon as it has the time to do something, it will do it, but it can't be done right away.
```javascript!
fetch('https://www.reddit.com/search.json?q=kittens')
.then(function(responseData) {
return responseData.json();
})
.then(function(jsonData) {
console.log(jsonData);
});
```
In this code snippet from the lesson materials, the `.then` is a *promise* because it says it will return the `.json` of whatever is is we get back after we fetch from reddit for kittens. Same with the console log. Neither of these things can occur until we fetch said data from reddit, of course.
In conclusion, sometimes (often) we need to wait a few fractions of a second for certain chunks of code to run before our code can execute properly. Probably the most common example of this is some kind of AJAX thing. We run some asynchronous code, have some promises to run once AJAX completes, and then our code continues on its merry way.
### Wednesday, March 15
**Grid**
Another way to do some layout stuff similar to flexbox. They can be used in conjuction if so desired. They are different, but accomplish similar goals. The main difference is that grid is based on a 2-dimensional grid of rows and columns.
Just like flexbox, in order to use its power, we need to set the `display` property of our desired grid area to be `display: grid`.
You then define the dimensions for the rows and columns of your grid. You can use both absolute and relative measurements, including the new `fr` or fractional unit, which is a fraction of the remaining area of the screen after the previously made rows and columns.
```javascript!
body {
display: grid;
min-height: 100vh;
grid-template-rows: 200px 1fr 120px;
grid-template-columns: 180px 1fr;
}
// here we have 3 rows, one that is 200 pixels, one that is 1 fractional unit, and one that is 120 pixels.
// similarly, we have 2 columns, one 180 pixels, and one that is 1 fractional unit.
```
### Thursday, March 16
#### OOP
Object Oriented Programing (OOP) is a method of organizing code into classes, or blueprints that allow us to quickly create new objects.
```javascript!
class Person() {
// the constructor function runs when a new instance of the object is created!
constructor(hairColor, heightInInches, eyeColor) {
this.hairColor = haircolor,
this.heightInInches = heightInInches,
this.eyeColor = eyeColor,
this.exampleProperty = "taco"
}
exampleMethod(): {
console.log("You can invoke this anywhere!")
}
}
// use the 'new' keyword to create an object, and then fill in the parameters in the same order they appear in your constructor method
let gabe = new Person("brown", 70, "brown")
console.log(gabe.hairColor)
// expected output: "brown"
console.log(gabe.exampleProperty)
// expected output: "taco"
// this one is to show that the values you set can be anything, and just often are the same name as the parameter for clarity's sake.
gabe.exampleMethod()
// expected output: "You can invoke this anywhere!"
```
#### Canvas
Canvas is a native HTML element used for drawing shapes on a page. It's very helpful for making browser games.
```javascript!
// always begin by setting the context of your canvas. Most often, this means setting it to be a 2d shape, which is how you gain access to all the methods available in canvas.
const ctx = canvas.getContext('2d')
// Fill Color
ctx.fillStyle = 'white';
// Line Color
ctx.strokeStyle = 'red';
// Line width
ctx.lineWidth = 5;
// creates a solid rectangle
ctx.fillRect(10, 10, 100, 100);
// creates a rectangle with just the outline
ctx.strokeRect(10, 10, 100, 100);
```
**Collision**
This part seems to trip people up a lot, probably because of the math part of it. When you create a shape in canvas and define its dimensions, you begin at the top left corner.
When calculating collision, you need to know the furthest distance in each direction for your shape. This is because you need this for the math part of it. You'll need to add the current `x` value or `y` value of your canvas element PLUS the respective `width` or `height`.
Think of it like the human body. If you were to run into a wall in your house, you don't consider yourself as having collided with the wall when your lungs or your ribcage collides with the wall (hopefully). You collide with the wall when your outermost distance collides with the wall. Comparing this to canvas, if your point of origin (your lungs, for example), PLUS a few inches, to make sure it's your outermost distance, is in the same place in space as the edge of the wall, you have collided.
```javascript!
// if you just look at this one, it probably says to you 'this seems wrong'. You don't want your lungs colliding with the wall, you want to give yourself a little more space than that.
function badDetectHit() {
if (lungLocation >= wallArea) {
return "oh no not the lungs!"
}
}
// this would now work for anything, as lungLocation + distanceBetweenLungsAndSkin always calculates to be where we would collide with something.
function goodDetectHit() {
if (lungLocation + distanceBetweenLungsAndSkin >= wallArea) {
return "still ouch but much better"
}
}
```