Here's my report for Tuesday:
Starting a bit later -- I'll have to make up this time later this evening. Especially since I have to go to a meetup tonight and do some networking.
Reviewing all the parts about refactoring:
Put it into Practice - Refactor our Website Part 1
1. keep all html selectors together (regular bold, h1, etc)
2. Notice which is doing specific things
1. don't apply to h1, rather to specific class - call it BigHeadings
2. add a class to h1 called big-heading
3. create section Headings in css file and put this h1's styles there.
3. All headings have same font, etc.
1. multiple selectors:
h1, h2, h3, h4, h5, h6 {
font-family: "Montserrat-Bold";
}
1. h2 styles
1. give h2's specific classes:
2. .price-text, font-size: 3rem, line-height: 1.5;
3. .big-heading, same
2. h3 styles
1. add .feature-title, for font-size
3. cta-heading turns out to be the same as .big-heading
1. add .big-heading to cta heading
4. text-align: center --ctrl f shows we used it 7 times
1. best to make the entire body text-align: center
2. But keep the one inside the media query
5. Regularly save and refresh and check that nothing changed
6. padding: 7% 15% --- used 4 times
1. change to .container-fluid
2. add container-fluid class to each item we used that padding for
1. don't even have to overwrite, just append it inside the quotes after what's already there.
2. delete all the extra stylings
3. pushes down our navbar
1. inspect
2. what should we do?
1. combine styles
2. make .container-fluid to have padding: 3% 15% 7% but also target the
#title .container-fluid {
padding: 3% 15% 7%;
}
Best way is to refactor as you go along so you don't have to have a huge refactoring session later.
Next lecture:
Advanced CSS - Combining Selectors
Pick & Mix Selectors
1. Multiple Selectors
- combine selectors using a comma (don't need a space but helps with readability)
- h1, h2, p {color: red;}
- most common for html elements
2. Hierarchical Selectors
- selector1 selector2 {}
- #title .container-fluid {}
- targeted the .container-fluid class that's inside a div with id #title
- spacing is important, different with the multiple selectors
- read right to left - very important -- parent child {}
- div h1 {}
- h1 that's inside of a div (too broad though)
- so we use the class name
- more common: .container-fluid h1 {}
- onlythe h1's within the parent with class container-fluid
3. Combined Selectors
- no spaces
- selector1.selector2 {}
- selector1#selector2 {}
- h1#title {}
- have to occur in the same element
- left to right
- does not work: div#title {}
- what's the difference?
- open codeply
1. no bootstrap framework
<div class="container">
<h1 id="heading" class="title">Hello world!</h1>
</div>
<div class>"container-fluid">
<h1 class=>"Good Bye World!</h1>
</div>
.container .title {
color: red;
}
this colors only Hello World red
if you delete the space, it's looking for both classes in the same element
.container.title {} with no space doesn't work
h1#heading {}
targets all of the h1's that have #heading
h1.title {} targets all the h1's that have a class title (will affect both hello and goodbye)
Angela stresses how important it is for refactoring and readability: try to add new combinations instead of adding new classes.
Next Lecture:
Refactoring our Code Part 2
Continuing now with combined selectors
1. repeated pattern: background with opposing text-color
- identify each section with white background
- add class: white-section to each
- identify each section with colored background
- add class colored-section to each
- add styles to these two selectors in CSS
- #testimonials is slightly different
- delete the repeated part (white text)
- over-ride the background color by applying background color to the ID
- ID is more specific so it will override
- CTA section gets deleted
- even if you have a combined selector, you can specify styles that you would originally specify only for single selectors
- #title {something}
- #title .container-fluid {something}
- just add it to #title .container-fluid{}
Ok, it's safe to say that refactoring is really important for any project. And that it's important to do it as you go along. That being said, I'm going to skip it for now and will apply it in the projects going forward. I'll use these notes as reference for how-to and best-practice.
Continuing to the next lecture:
Advanced CSS - Selector Priority
I think Angela's starting to get tired by this point because she didn't give much of an intro here, granted it's a short lecture video.
In codeply, she gives an example of color:
h1 {
color: red;
color: green;
} html elements have the lowest priority
I you try to change the same property twice, the last rule change (the green) will be carried out. Code is being read top to bottom.
A class is more specific than an html element:
.title {
color: yellow;
} this has higher priority than the h1 element
#heading {
color: blue;
} this has the highest priority
inline CSS style-"" has even higher priority than even the id selector in styles.css.
How can you prevent creating conflicting rules?
- use ID's only very very sparingly - 1 name must only be used once
- e.g., ID's were only used for the section tags in the tindog html
- multiple classes: avoid as much as possible -- it's a pet peeve for a lot of people
- inline style: avoid as much as possible -- considered bad practice
Next lecture:
Completing the Website
Refactoring:
-it's great to combine selectors, but sometimes it's not necessary to combine if you have one or two classes that have the same styles. -- in reality, it won't or will very rarely be the case. Most often will choose different styles for almost every class.
Oh, I caught a mistake I had made. She centered the entire section for the media query, where I just centered the text only. Makes sense. Oh wow and that fixed my menu problem of it coming up on the left side instead of the center like hers.
Oh man, what happened to my font awesomes? they all disappeared!
<script defer src="https://use.fontawesome.com/releases/v5.0.7/js/all.js"></script>
<script src="https://kit.fontawesome.com/2356c19003.js" crossorigin="anonymous"></script>
I added my own kit code to angela's complete version. icons didn't work. I opened up firefox and they worked fine. there's some sort of bug with chrome that I think this article on stack overflow mentioned -- ah nevermind, they're working now. It was an issue on stack overflow's side.
Next Lecture:
Tip from Angela - Building a Programming Habit
- Tag your new habit on the end of an existing habit.
- "every morning after I brush my teeth, I'm going to meditate."
- brushing her teeth became a trigger for meditating
_________________________________________________________________________________________
Next Section: Introduction to Javascript ES6
First Lecture: Introduction to Javascript
Netscape - people who recognize it are over 30
Andreesen Horowitz -- Mark Andreesen
Mosaic - a browser Mark worked on in college
mark worked on Netscape after college
browser wars - IE vs Netscape
Netscape died
tech incorporated into Firefox
1995 - HTML all form, no function
Netscape wanted something different. existing system had server sending functionality to the user's browser. They wanted to take away the server and have the code run on the browser.
Code had to be easy, so non-programmers could use it to add functionality to websites.
Brendan Eich - contracted by netscape to create this language. Made JavaScript in 10 days.
Turn off JS in your browser and see what happens. go to twitter and it'll go straight to the mobile version which doesn't use JS. writing a tweet misses functionality of character limit
Viewing New york Times w/o JS: ads won't load
YouTube won't load
Brendan Eich first called it LiveScript.
Microsoft called it JScript
Europeans tried to standardize it and called it ECMAScript (you can see versions called ES 5 or ES 6)
What does 'script' mean?
Like a script in a theatrical play
Java vs JavaScript
What's their relationship? Java and JavaScript have has much in common as car and carpit -- in 90's, the word Java was extremely popular for some reason.
Java is a compiled language
JavaScript is an interpreted language
Interpreted
"like toy languages"
line by line
slow
Compiled
"serious"
fast
Literally Supported by every browser
Most popular language of 2018 was still JavaScript.
Which language should I learn?
iOS: swift
build android app: Java
Websites/Web-Apps: JavaScript -- best friend and worst enemy
Next lecture
Javascript alerts -- adding behavior to websites
- Open new tab in chrome
- Open console: view, developer, javascript
- Write:
- alert("Hello");
- hit enter
- brings up a popup with the "hello" alert. click ok and popup disappears
- Downside of console
- muliple alerts, aka a multi-line instruction, won't be executed
- hold down shift to add more lines
- Another way to write code without this
- Click on 'Sources'
- Right arrow, click 'Snippets"
- Click 'New Snippet'
- call it index.js
- Now you can write JavaScript like you do in Atom
- Then push the play button in the bottom right-hand corner
- We'll be using the Snippets editor in the next few lessons
- Which instructions are ignored?
- fake commands
- crash the console and reports error
- MDN Documentation
- JavaScript
- tutorials, references, or search
alert() keyword -- short version of window.alert()
grammar, aka the syntax, of alert:
function: alert
Message: ("Hello")
End: ; - semicolon
quotation marks: a word processor will show different symbols for open and closing quotation marks.
For coding, editors will always give you the same symbol for both
You'll get errors if you copy and paste from a word processor
Stylistic choices/convention:
- spaces between parenthesis and quotes
- double quotes over single quotes
- sometimes situations where single quotes are preferred
- if you ever get confused about which stylistic choices to make, bookmark the living document on github
- https://github.com/rwaldron/idiomatic.js
- key message: all code in any code-base should look like a single person typed it
- this document is kind of the classic 'The Elements of Style' for writing with the english language (this book is used in college a lot)
Data Types
- string
- called because it's a string of characters
- not interpreted as code
- numbers
- boolean
- true
- false
typeof() function - tells you the data type of something
in chrome javascript console, add numbers
alert(2+3);
JavaScript Variables
prompt("What is your name?");
box opens up and has a field for you to type text in and press ok
How do we have chrome remember what we type?
var myName = "Angela";
Keyword: var
Name: (the name of the variable)
Value: "Angela"
Angela presents a nice animation where the variable is a box/container and the value is the contents of that container.
once you've created a variable with var, you don't need to use it ever again.
Had to minimize one part of the sources to get the arrow menu which had Snippets on it. Also didn't realize I could have the console on the bottom at the same time as having the snippet area up.
var myName = "Josh";
var yourName = prompt("What is your name");
alert("My name is " + myName + ", welcome to my course " + yourName + "!");
Naming and Naming Conventions for JavaScript Variables
clear the console, ctrl+k (doesn't delete variables)
or right click and choose clear console
to erase data (variables, etc), right-click on the reload button and choose "clear cache and hard reload"
- give every variable a different name
- can't use javascript keywords as a variable name
- but you could combine: myvar
- no spaces
- spaces are read as separate
- only letters, numbers, dollar sign ($), or underscore (_)
- no dash (-)
- camel casing
- thisIsGoodPractice
- TherapistFinder.com
- easier to read and less frightening than therapistfinder.com
Strings
Concatenation
combine strings using the plus sign (+)
"a" + " " + "b" = "a b"
start off with a var for message
then another var for name
write a code for popup or alert that combines these two variables
var message = "I'm happy to see you";
var name = "Josh";
alert(message + ", " + name + ".");
String Lengths and Retreiving the Number of Characters in a String
length property
word.length --- will give us number of characters
var name = "Angela";
name.length;
name.length will return 6
write code to create a prompt to enter a long string
report back to the user how many they've written
tell them how many they have left
var novel = prompt("Type your message here. Remember it must be within 280 characters: ");
var lengthDiff = 280 - novel.length;
alert("You have written " + novel.length + " characters. You have " + lengthDiff + " remaining.")
variation:
use parenthesis inside the alert for the arithmetic instead of creating a new var like I did
comments:
- two forward slashes, //, for a single line comment
- forward slash and star, /*
Slicing and Extracting Parts of a String
take off the extra characters so you don't show a negative number for character remaining when you go over (like on twitter)
slice(x,y) function
turn your code into comments: ctrl + / (while highlighted)
var name = "Angela";
name.slice(0,1);
the numbers are start, finish - each number is an index for the location of the character within the string.
numbers start with 0 in almost anything in computer science
excludes the second index
abc
to slice and extract the first character, slice(0,1)
to get the first 3 characters: slice(0,2)
to get just the last 2 characters: slice(1,3)
write an alert to cut down your tweet to 140 characters
var novel = prompt("Type your message here. Remember it must be within 140 characters: ");
alert("Here is your tweet: " + novel.slice(0,140))
Challenge: Changing Casing in Text
toUpperCase() -- change everything in a string to capital letters
word.toUpperCase()
var name = "Josh";
name.toUpperCase();
or change our variable to all upper case:
name = name.toUpperCase();
also change to lower case: toLowerCase()
var name = prompt("What is your name?");
alert("Hello " + name):
create a prompt asking user for their name. if they give upper case or lower case, change it so that only the first character is capitalized and the rest lower case.
var name = prompt("What's your name?");
var first = name.slice(0,1);
var rest = name.slice(1,name.length);
var capital = first.toUpperCase();
var small = rest.toLowerCase();
alert("Nice to meet you " + capital + small + ".");
1. store a var that user enters via prompt
2. Capitalize the first letter of their name
1. isolate the first character
2. turn the first character to upper case
3. isolate the rest of the name
4. concatenate the first char with the rest of the chars
3. Use the capitalized version of their name to greet them using an alert
Angela used the console to check each line of the code as she thought through it and verified that she had the right index numbers in slice().
looks like I went further and used toLowerCase in the case that the user gives all capitlized letters
essential skill:
take a big problem
break it down into small pieces
and work on each one by one
Edge Cases: important to address because you'll have thousands of users using your website/app/program
Basic Arithmetic and the Modulo Operator in JavaScript
Modulo
var e = 9 % 6;
modulo, % gives the remainder of a division
12%8 = 4
using %2, 0 means an even number, 1 means an odd number
var cost = 3 + 5 * 2
precedence: same as in math -- multiplication first, then addition
Parentheses: (3+5)*2 -- always executed first
When you want to keep multiplication first, good practice is to always put it into parentheses (), even though multiplication is always first anyways.
Challenge: Dog Age to Human Age Formula
humanAge = (dogAge - 2) x 4 + 21
create a prompt asking the user for the age of their dog
convert to human age
report back to user through an alert
var dogAge = prompt("Please enter the age of your canine: ");
var humanAge = (dogAge-2)*4+21;
alert("Your canine's age as a human is: " + humanAge + ".");
Increment and Decrement Expressions
Increase by 1:
var x = 5;
x = x+1;
x++ is the same expression, known as the increment expression
Decrease by 1:
x=x-1;
x-- is the same, called the Decrement expression.
increase by more than one:
+=
x += 2
works with variables:
var x = 5;
var y = 3;
x += y; //this equals 8 and sets x equal to 8 as well
works with all the other operators:
+=, -=, *=, /=
Quiz
there's a question that doesn't seem correct
var x=3;
var y=x++;
y+=1;
correct answer says 4, but I think it would be 5
Functions Part 1: Creating an Calling Functions
keyword: function
name
parentheses
curly brackets with code inside:
function name() {
}
keyword 'function' is only used when you create the function
calling the function, you just need the name and parentheses: getMilk();
Angela used a cute animation of a robot and instructions (using the alert function) for each step telling the robot going to the store to by some milk. Then she each instruction and put it into her function getMilk();
Syle:
when creating a function, indent all the code inside of the curly braces.
Angela uses console.log now instead of alerts (which you have to click through in chrome).
difference between console.log and alert:
console.log shows only in the console -- it's meant for the developer for messages, especially those related to debugging
Challenge
http://stanford.edu/~cpiech/karel/ide.html
Write your own functions
1. Use Karel the robot (click link)
2. change to 5x5
3. notice function main()
4. Karel takes commands -- see the reference
5. Make a function, separate from main
6. Call it in main
7. Challenge: write code to move karel all the way to the upper right corner in the 5x5
/**
* Welcome to the Stanford Karel IDE.
* This is a free space for you to
* write any Karel program you want.
**/
function main(){
//your code here
traveltoEdge();
turnLeft();
traveltoEdge();
}
function traveltoEdge() {
move();
move();
move();
move();
}
Functions allow us to remove repitition as well as identify errors.
Write code to command karel to put down beepers in a patter: a diagonal line from bottom left to upper right corner. Use least repetitive way possible, using functions.
function main(){
//your code here
putBeeper();
putSecondBeeper();
putRest();
}
function putSecondBeeper(){
move();
turnLeft();
move();
putBeeper();
}
function putNextAfterTwo(){
turnRight();
move();
turnLeft();
move();
putBeeper();
}
function putRest(){
putNextAfterTwo();
putNextAfterTwo();
putNextAfterTwo();
}
Optional challenge:
Get Karel to create a chess board pattern.
function main(){
//your code here
twoBeeperRow();
upRightSide();
threeBeeperRow();
upLeftSide();
twoBeeperRow();
upRightSide();
threeBeeperRow();
upLeftSide();
twoBeeperRow();
}
function twoBeeperRow(){
move();
putBeeper();
move();
move();
putBeeper();
move();
}
function threeBeeperRow(){
putBeeper();
move();
move();
putBeeper();
move();
move();
putBeeper();
}
function upRightSide(){
turnLeft();
move();
turnLeft();
}
function upLeftSide(){
turnRight();
move();
turnRight();
}
Solution is pretty much the same!
Next lecture has me copying the following code in advance:
function getMilk() {
console.log("leaveHouse");
console.log("moveRight");
console.log("moveRight");
console.log("moveUp");
console.log("moveUp");
console.log("moveUp");
console.log("moveUp");
console.log("moveRight");
console.log("moveRight");
console.log("moveLeft");
console.log("moveLeft");
console.log("moveDown");
console.log("moveDown");
console.log("moveDown");
console.log("moveDown");
console.log("moveLeft");
console.log("moveLeft");
console.log("enterHouse");
}
Functions Part 2: Parameters and Arguments
Functions come in 3 classic flavors. what we just learned was like vanilla -- the first and most basic.
Parameters - input between the parentheses
we're going to specify bottles of milk into getMilk
function getMilk(bottles) {
var cost = bottle * 1.5;
//do something with cost
}
Functions that take parameters are like chocolate, slightly more functionality and do a lot more.
function getMilk(bottles) {
console.log("leaveHouse");
console.log("moveRight");
console.log("moveRight");
console.log("moveUp");
console.log("moveUp");
console.log("moveUp");
console.log("moveUp");
console.log("moveRight");
console.log("moveRight");
console.log("buy " + bottles + " bottles of milk");
console.log("moveLeft");
console.log("moveLeft");
console.log("moveDown");
console.log("moveDown");
console.log("moveDown");
console.log("moveDown");
console.log("moveLeft");
console.log("moveLeft");
console.log("enterHouse");
}
getMilk(12);
Challenge:
Change the code to take money instead of bottles. Calculate how many bottles the robot is able to buy. give your robot $10 and milk cost $1.50, how many bottle of milk can he buy?
function getMilk(budget) {
console.log("Buy " + (budget/1.5) + "bottles.");
}
Angela created a var for the division
And she also addresses non-intergers
How do we round in JavaScript?
Math.floor(number goes here);
var numberOfBottles = Math.floor(budget/1.5);
Outputs and Return Values
Functions that are able to give output
return -- keyword for a function to output a value
in her getMilk() function, she put a line at the end:
return budget % 1.5;
which is the change for what we bought, so we'd we could even specify that in a variable:
var change = getMilk(4);
We can assign a function that returns a value. Here, we're using the function to define a variable.
she creates a function to use in the main function to calculate how many bottles of milk.
then she creates a function to return the change
she then places both in the function
function getMilk(money, costPerBottle) {
console.log("leaveHouse");
console.log("moveRight");
console.log("moveRight");
console.log("moveUp");
console.log("moveUp");
console.log("moveUp");
console.log("moveUp");
console.log("moveRight");
console.log("moveRight");
console.log("buy " + calcBottles(money, costPerBottle)+ " bottles of milk");
console.log("moveLeft");
console.log("moveLeft");
console.log("moveDown");
console.log("moveDown");
console.log("moveDown");
console.log("moveDown");
console.log("moveLeft");
console.log("moveLeft");
console.log("enterHouse");
return calcChange(money, costPerBottle);
}
function calcBottles(startingMoney, costPerBottle) {
var numberOfBottles = Math.floor(startingMoney / costPerBottle);
return numberOfBottles;
}
function calcChange(startingAmount, costPerBottle) {
var change = startingAmount % costPerBottle;
return change;
}
console.log("Hello master, here is your " + getMilk(5, 1.5) + " change.");
Challenge: Create a BMI Calculator
Angela's included the formula for BMI:
create a function hat take weight and height as inputs and give the output that's equal tot he BMI
copy index.js contents and use the chrome developer tools
function bmiCalculator(weight, height) {
return Math.round(weight/(height*height));
}
var bmi = bmiCalculator(65,1.8);
alert("Your BMI is approximately " + bmi + " kilograms per square meter.")
I had at first used toPrecision, but the assignment didn't like that solution. It told me I had to round.
So I checked the MDN docs and used Math.round with the calculation inside the parentheses.
Angela's solution:
function(weight, height) {
var bmi = weight / (height * height);
return bmi;
}
raise to the power of 2 in javascript: googling the docmentation:
Math.pow(base, exponent)
Math.pow(height, 2)
function(weight, height) {
var bmi = weight /Math.pow(height, 2);
return Math.round(bmi);
}
Tip from Angela - Set Your Expectations
Coding isn't easy. It's not realistic to think that you aren't smart because you don't udnerstand soemthing because it is in fact hard.
Conversely, it can be easy to think that it's impossible. But the only difference between a master and a beginner is the amount of work that that person has been able to put in.
10,000 hours!
I have to go to a networking meetup and try to get some information from some engineers about learning and careers.
I'll continue later on into the night.
_____________________________________
Later tonight lol it's now 10:13 and starting again
Next Section:
Intermediate Javascript
First Section
Random Number Generation in JavaScript: Building a Love Calculator
Random number Generation
var n = Math.random();
any number between 0 and 0.9999999999999999
16 decimal places
never reaches 1, but can be 0.0000000000000000
see MDN documentation for Math.random() where it says:
"The Math.random() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user."
this let's us generate over a billion numbers
var n = Math.random()
n=n*6; //multiple the number by the cap you want -- this one will never reach 6
n = Math.floor(n) + 1; //round down to nearest integer so that it returns any integer between 0 to 5
console.log(n); //print out to console
Extra resource for randomness: https://www.youtube.com/watch?v=GtOt7EBNEwQ
Math.random() isn't useful until we scale it. multiply by the desired cap, then use Math.floor to round down to nearest whole integer.
Add one to get random 1 though 6
Challenge:
1. create a love calc
2. two prompts for names of two people
3. generate a number between 1 and 100
4. give info back to user as an alert giving their love score
var name1 = prompt("Please enter the name of a person.");
var name2 = prompt("Please enter the name of the love interest of that person.");
var loveScore = Math.random();
loveScore*=100
loveScore = Math.floor(loveScore)+1;
alert("The love score of " + name1 + " and " + name2 + " is " + loveScore + "%.");
Control Statements: Using If/Else Conditionals and Logic
need to evaluate if statement is true
control flow: if/else logic statements
if (track === "clear") {goStraight();}
else {turnRight();}
3 equal signs back to back check for equality in JavaScript conditional statements
beautification is important for readability:
if(track === "clear") {
goStraight();
}
else {
turnRight();
}
for out love calculator:
if(loveScore === 100) {
alert("Your love score is " + loveScore + "%. " + "You love each other like Kanye loves Kanye.");
} else {
alert("Your love score is " + loveScore + "%. ");
}
Comparitors and Equality
Is equal to ===
is not equal to !==
<, >, <=, >=
two instead of three equal signs? what's the difference?
var a = 1;
var b = "1";
if (a===b) {
console.log("yes");
} else {
console.log("no");
}
this will show "no" because a is a number and b is a string. however, if you use == it will show yes
three equal signs checks datatype as well as value. == only checks for value
what if we could separate the love score ranges further, more than just one or two ranges. use AND and OR
Combining Comparators
above 30, but below 70
combine comparators:
&& and
|| or
if(loveScore > 30 && loveScore <= 70) {
alert("");
}
if (loveScore <= 30) {
alert();
}
Assignment: BMI Calculator Advanced (IF/ELSE)
function bmiCalculator (weight, height) {
var bmi = weight / Math.pow(height, 2);
var interpretation = "";
if(bmi<18.5){
interpretation = "Your BMI is " + bmi + ", " + "so you are underweight.";
} else if (bmi>=18.5 && bmi<24.9) {
interpretation = "Your BMI is " + bmi + ", " + "so you have a normal weight.";
} else if (bmi>=24.9) {
interpretation = "Your BMI is " + bmi + ", " + "so you are overweight.";
}
return interpretation;
}
yay, it's correct
Collections: Working with JavaScript Arrays
store multiple items into an array
in Angela's example, names of invitees to check to see if they were invited to her party to make sure too many uninvited people come
var myEgg = eggs[1];
var eggs = [🥚,🥚,🥚,🥚,🥚,🥚,🥚,🥚]
must use square brackets
position is called index and starts from 0
eggs[1]
eggs.length = 8
var guestList = [];
whenever you see square brackets, it usually is related to a collection data type -- most often arrays
var guestList = ["Angela", "Jack", "Tim"];
console.log(guestList[0]);
use function includes() to see if the array contains that specified item -- eggs.includes()
write code to create a prompt that asks for guest's name
check the array for that name
if it exists tell them welcome
if it doesn't, tell them they aren't on the guest list
var guestList = ["Angela", "Jack", "Tim", "James", "Jason"];
var stranger = prompt("Please enter your name: ");
if(guestList.includes(stranger)) {
alert("Welcome to the party, " + stranger + "!");
} else {
alert("I'm sorry, you aren't on the guest list.");
}
Angela called her variable guestName. stranger is more fun, in my opinion
Angela ended the lecture with a bad joke:
Why did the programmer quit his job? Because he didn't get arrays.
Adding Elements and Intermediate Array techniques
computer science degrees apparently don't prepare people to actually code. 1 out of 200 applicants can't write good code.
from coding horror website
fizz buzz fizzbuzz game
kids saying number 1 after another
if divisible by 3, fizz, by 5, buzz, both fizzbuzz
get code to print out sequence of numbers starting by 1
var output = [];
output.push(1);
push adds the specified contents to the array. always adds to the end of the array.
pop take off the last item of the specified array. output.pop;
make a function to automate adding numbers to the array
var output = [];
function fizzBuzz() {
console.log(output);
}
Challenge: add to the function such that when you call it, a new item will be added to the array, increments by one.
function fizzBuzz() {
var n = 0;
output.push(n+1);
console.log(output);
}
---------------------------
var output = [];
var n = 0;
function fizzBuzz() {
n = n+1;
output.push(n);
console.log(output);
}
Angela's:
var output = [];
var count = 1;
function fizzBuzz() {
output.push(count);
count++;
}
Instead of putting 3, enter "fizz" into the array, buzz for 5, fizzbuzz for both
Use the modulo -- if remainder is 0, that means the number is divisible by the number you chose to divide by -- in this case, 3 and 5
var output = [];
var count = 1;
function fizzBuzz() {
if(count%3===0 && count%5===0) {
output.push("fizzbuzz");
} else if(count%3===0) {
output.push("fizz")
} else if(count%5===0) {
output.push("buzz");
} else {
output.push(count);
}
console.log(output);
count++;
}
yay I got it.
I just realized, you have to execute the script before you can use the function in the console.
Ah, I was right to put the check for both at the top of the if chain (sorry, I should say 'control flow').
the order of your if statements matters.
link to a funny story of an engineer who automated his entire work life with code
https://www.jitbit.com/alexblog/249-now-thats-what-i-call-a-hacker/
Control Statements: While loops
simplest type of loops are while loops
while (condition) {
do something
}
---------------------------------------
var i=1;
while (i<2) {
console.log(i);
i++;
}
automate fizzBuzz so we don't have to manually call it in console
var output = [];
var count = 1;
function fizzBuzz() {
while(count <= 100) {
if(count%3===0 && count%5===0) {
output.push("fizzbuzz");
} else if(count%3===0) {
output.push("fizz")
} else if(count%5===0) {
output.push("buzz");
} else {
output.push(count);
}
count++;
}//while
console.log(output);
}//function
problem with while loops is that they will run infinitely until the statement becomes false. If you forget to increment the count variable, it will just run forever and crash your system (chrome in this case).
apple called their loop at their HQ 'infinite loop'
Bad joke:
A programmer's wife told him "while you're at the store, get some milk." And he never came back
Baby woke up, so I turned the computer off so the glare wouldn't distract her from nursing. |