The Web Developer Bootcamp - Colt Steele

Introduction to This Course

A Note on Asking for Help

Hi everyone!

As you work your way through the course, you are bound to run into trouble with your code. But don't worry, because we are here to help! You are always welcome to post a question in the Q&A board, but before you do, please read through the following so we can best assist you with your question. First, before asking a question, use the Q&A board search bar to determine whether or not the question has already been asked (and answered). If you cannot find a solution to your problem then please feel free to post a thread of your own.

‌ When posting a question, one thing that is really important for us to help you out is remembering to provide enough context around your code. It's very hard for us to debug anything without seeing your exact code. You can share your code with us in a Q&A thread by using the {...} code block button (first write your code, select it, then press the button). However, when possible, we prefer to see your code in a live environment so it can be run right away and debugged more easily.

Here are some easy ways to share your code with us (and for us to share any tweaks or solutions that we find, in return):

They all work great to share code. It's really a matter of preference.

Another important resource that we highly recommend is a screenshot sharing app called Gyazo. If you're trying to show us how something looks in your browser or on your machine, it really helps us to see a screenshot. Gyazo lets you take a screenshot and then it automatically uploads it for you. It's really fast, and I actually used it for some of the screenshots I made in this course. Udemy also allows you to upload screenshots from your computer via the image button (to the left of the code block button).

One last thing, if you ask a question then realize that you need to edit it, please edit the question directly instead of adding a comment with updated information. The reason being, if you answer your own question with a comment then it gets marked as answered and removes itself from our unanswered questions notification system. The edit button can be found in the top right corner of your posted question by clicking on the three vertical dots and selecting the Edit option. Likewise, if another students answers your question, but the answer is not satisfactory, then you will need to either ask a new question or send a link to your current question as a direct message to our course TA.

If you have any questions about any of the resources I recommended, please let us know. Also, if you have other resources that you prefer to use, please share them with us! Enjoy the rest of the course!

Colt.


Additional Free Content

Follow my YouTube Channel for additional free content. I send out polls to my subscribers to help determine which videos I teach next. If you want to participate and steer the course of the channel, subscribe and turn on notifications. Otherwise, enjoy the free content!


Introducing our TA

I have some important news about the course that I’m very excited to share with you: We have a brand new TA! It took three weeks of searching and interviews with 14 different candidates, but in the end I found the perfect person for this role. I’m thrilled to introduce you to Ian Schoonover who will be helping out on the discussion boards and chatroom's starting immediately. ‌ I first met Ian a few years ago when he was a student in one of my back-end development evening courses. He’s a natural teacher. Even before he graduated the class he was already spending time helping other students debug their code. He subsequently TA’d for me at General Assembly, and most recently he worked with me at Galvanize in San Francisco. He’s a great guy who has both worked as a developer and a teacher. He knows this material front and back and has lots of experience helping new developers debug and improve code. We are very lucky to have him on the team! ‌ It’s very important to me that this course has an active community around it. I have seen many online courses that offer zero student support and basically leave students to fend for themselves. I do not want this course to work that way. I know that the difference between waiting a few hours to get help and waiting a few days for help can often be the difference between continuing to learn and giving up on programming all together. Obviously we cannot guarantee the on-demand assistance of an in-person course, but we are going to do our best to make sure no one waits very long to get help. ‌ We are so fortunate to already have a great community centered around this course, and it’s only going to get better and better with the hiring of Ian. I highly encourage you to make the most of this awesome community if you are not already. Here are a few different ways I hope you can participate: ‌ In the chatrooms ‌

  • Introduce yourself
  • Post your own solutions to projects and exercises
  • Share links to helpful articles and tutorials
  • Share your own blog posts (shoutout to Jamal Yusef for some great content)
  • Share your personal projects
  • Make people laugh

‌ In the Q&A ‌

  • Ask questions
  • Help answer other students’ questions
  • Share feedback on individual lessons, sections, and the course in general

‌ See you out there! ‌ Colt


Join the Online Community

Hi everyone, ‌ In my opinion, the very best part of this course is the active online community we have centered around it. ‌ Some huge components of that community are the course Facebook Group (NEW!) and Discord Channels (NEW!) ‌ I highly recommend that you join one or both of the communities ASAP, so you can start chatting with thousands of other students. ‌ Also, if you're interested in further learning resources, I have a growing YouTube channel with videos that cover various topics like Recursion, Bitcoin, and the JS Call Stack. ‌ Ian, one of our course TA's, also has a YouTube channel that augments course projects and topics like YelpCamp and looping in JS. While you're there, be sure to check out some of the Web Developer Bootcamp: Student Success Stories, where students like yourself talk about their journey through the course and how it affected their careers. ‌ We hope to see you around any or all of these social outlets! Thanks for being a valued member of our online community. ‌ Colt


Why This Course

This course is for everyone and will take people from beginner to advanced. It's also taught by a professional. 94% of Colt's in-person bootcamp graduates go on to get web developer jobs. This course also cover full-stack JavaScript and Node.JS. The program is constantly updated with new content, projects, and modules. This is the only course you will ever need to learn web development.


Syllabus Download

Course Outline / Syllabus


Syllabus Walkthrough

  1. Introduction to this Course
  2. Introduction to Front End Development
  3. Introduction to HTML
  4. Intermediate HTML
  5. Introduction to CSS
  6. Intermediate CSS
  7. Bootstrap (3)
  8. Bootstrap 4!
  9. Bootstrap 4: Flexbox and Layout
  10. Introduction to JavaScript
  11. JavaScript Basics: Control Flow
  12. JavaScript Basics: Functions
  13. JavaScript Basics: Arrays
  14. JavaScript Basics: Objects
  15. DOM Manipulation
  16. Advanced DOM Manipulation
  17. Color Game Project
  18. Intro to jQuery
  19. Advanced jQuery
  20. Todo List Projects
  21. OPTIONAL Project: Patatap Clone
  22. Backend Basics
  23. The Command Line
  24. Node.JS
  25. Server Side Frameworks
  26. Intermediate Express
  27. Working With API's
  28. YelpCamp: Basics
  29. Databases
  30. YelpCamp: Data Persistence
  31. RESTful Routing
  32. Data Associations
  33. YelpCamp: Comments
  34. Authentication
  35. YelpCamp: Adding Authentication
  36. YelpCamp: Cleaning Up
  37. YelpCamp: Update and Destroy
  38. YelpCamp: UI Improvements
  39. Git and GitHub
  40. Deploying
  41. JavaScript: The Tricky Stuff

Lecture Slides

Lecture Slides ‌ Hi Everyone! ‌ You can find downloadable PDF versions of the course slides, here. ‌ Also, a past student shared some pretty comprehensive course notes that may be helpful as you progress through the course, you can find them here. ‌ Cheers, Ian Course TA


Introduction to Frontend Development

Unit Objectives

Objective 1. Setup Developer Environment.

Objective 2. Compare and contrast frontend and backend.

Objective 3. Define roles of HTML, CSS, & JavaScript.


Note About Setting up Frontend Developer Environment

Hello Everyone! ‌ In the following lecture you will learn how to setup your front-end environment.

‌ Here's a couple tips that will help you as you're getting set up.

‌ You can use Sublime Text 3 instead of 2. This will make it to where the HTML 5 <!DOCTYPE html> is included in your HTML boilerplate snippet.

‌ Also, when you're using the html + tab tab completion shortcut, be sure that the file's syntax is set to HTML. It should say "HTML" in the lower right corner of the window. If it says "Plain Text" then you'll need to click it and change it to "HTML" before the tab completions for HTML tags will work properly. ‌

Cheers, Ian Learn more


Setting up Frontend Developer Environment

For text-editing we'll use Visual Studio Code and for our Dev Tools either Chrome or Brave (which runs on Chromium)


Introduction to the Web

Internet Basics

  • Understand how the internet works (high level)
  • Understand the difference between frontend and backend
  • View the HTML on any given website.

‌ When you Google www.udemy.com, your request is submitted to your ISP and then within your ISP, the DNS takes the domain name and turns it into an IP address. Then, a request is sent to the desired IP address via HTTP. Your request finds the fastest path possible to the server with the specified IP. It's not a direct journey however, because it requires hopping from server to server until we arrive. The requested server figures out exactly what we're looking for (/courses). Then the server builds us the right content, often pulling information from the database. Then the server responds with any combination of HTML, CSS, and JavaScript. ‌ You can view the source code of any website, the HTML CSS and JavaScript, by right clicking and clicking view page source. Video Explanation


The Frontend Holy Trinity

Frontend basics. HTML, CSS, and JavaScript.

Objectives.

  • Understand the difference between frontend and backend code
  • Understand the roles of HTML, CSS, and JavaScript

Frontend vs Backend

  1. The frontend is the stuff that you see and interact with: HTML, CSS, and JavaScript
  2. The backend is everything else: so many choices!
  3. Restaurant analogy: The backend is everything that happens in the kitchen; the frontend is what is plated and sent to your table

HTML

  • Hyper Text Markup Language
  • Defines the structure of a webpage
    • “Put an image here”
    • “Put a form here”
  • The “nouns” of a webpage

CSS

  • Cascading Style Sheets
  • Defines the style of HTML
    • “Make all text purple”
    • “Give the first image a yellow border”
  • The “adjectives” of a webpage

JavaScript

  • Adds logic and interactivity to a page
    • “Do some math”
    • “Change color when the user clicks”
    • “Load new data from twitter”
  • The actions or “verbs” of a webpage

Introduction to HTML

Unit Objectives

Objective 1. Write properly structured HTML documents.

Objective 2. Write common closing and self-closing tags.

Objective 3. Recreate a simple website based on a provided photo.


HTML Basics

Objectives

  • Write simple HTML documents
  • Understand the difference between closing and self closing tags
  • Write tags with attributes
  • Use MDN as a reference
  • Given an image, write the corresponding HTML

History of HTML

  • Created in 1989/1990
  • Allowed publishing and exchanging of scientific and technical documents
  • Allowed electronic linking of documents via hyperlinks

The general rule

<tagName>Some Content</tagName>

Note About Introduction to MDN

Hi Everyone! The link in the next video, "Introduction to MDN" for MDN's Introduction to HTML can now be found here.

The MDN page has been updated since the making of this course so it won't appear exactly like what Colt has in the video. If you want to view the original version from when Colt recorded the video then see here for an archived version of the webpage before it was updated. cheers, Ian


Introduction to MDN

MDN, or Mozilla Developer Network, is a good resource for coding knowledge and answers for questions you might have regarding HTML, CSS, and JavaScript.

MDN


HTML Boilerplate and Comments

In Visual Studio Code and most popular code editors, we can type html and press tab and it will give us a HTML boilerplate template. Pressing tab will also autocomplete most tags in our text editor as well. Every HTML document will have a boilerplate, it should look something like this.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body></body>
</html>

We then put all of our content into the body and all of our scrips and other head elements into the head.

If we want to make a comment in our code, we can press lctrl+/

The title tag determines what the tab displays at the top of the browser and determines some of the sites SEO along with meta tags.


Basic Tags

These are some of the common tags that we'll see in HTML.

<h1>I'm a header</h1>
<h2>I'm a slightly smaller header</h2>
<h6>I'm the smallest header</h6>
<p>I'm a paragraph</p>
<button>I'm a button!</button>
<ul>
<li>List Item 1</li>
<li>List Item 2</li>
</ul>
<ol>
<li>List Item 1</li>
<li>List Item 2</li>
</ol>

Block level elements, such as <p>, each take up their own line in the HTML structure.

Semantic markup means we should make our HTML meaningful, an example is we would use <strong> over <b>.


HTML Lists

Ordered lists look like this.

<ol>
<li>Red</li>
<li>Orange</li>
<li>Yellow</li>
</ol>
// 1. Red // 2. Orange // 3. Yellow

Unordered lists look like this.

<ul>
<li>Red</li>
<li>Orange</li>
<li>Yellow</li>
</ul>
// * Red // * Orange // * Yellow

A nested list looks like this.

<ol>
<li>Red</li>
<li>Orange</li>
<li>
Yellow
<ul>
<li>Sunflower</li>
<li>
Banana
<ol>
<li>Frozen</li>
<li>Non</li>
</ol>
</li>
</ul>
</li>
</ol>

HTML Lists Assignment

Recreate this image using HTML

HTML Lists Assignment

Completed Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>HTML Lists Assignment</title>
</head>
<body>
<h1>Things I've Learned</h1>
<h2>Internet Basics</h2>
<ol>
<li>HTTP Requests</li>
<li>IP Address</li>
<li>Servers</li>
</ol>
<h2>HTML</h2>
<ul>
<li>Stands for <strong>Hyper Text Markup Language</strong></li>
<li>
Lots of tags
<ul>
<li>
Boilerplate
<ol>
<li>Doctype</li>
<li>HTML</li>
<li>
Head
<ol>
<li>Title</li>
</ol>
</li>
<li>Body</li>
</ol>
</li>
<li>Headings</li>
<li>Paragraph</li>
<li><em>em</em></li>
<li><strong>strong</strong></li>
</ul>
</li>
</ul>
</body>
</html>

Divs and Spans

A div is a generic container for flow content and used for simply grouping things together.

Divs are block level element which means that it will take up its own line.

Span is a inline block container. Span is mainly for selecting blocks of content that we want to keep inline.


HTML Attributes

Adding additional information to HTML tags.

<tag name="value"></tag>
<img src="corgi.png" />
<p class="selected">Woof Woof</p>
<a href="www.google.com">Click me to go to Google</a>
<link rel="stylesheet" type="text/css" href="style.css" />

Some tags, like the img tag, are self closing so all we need is an attribute or source.

Links in HTML

<a href="url">Link Text</a>
<a href="www.google.com">Click me to go to Google</a>
<a href="www.reddit.com">Click me to go to Reddit</a>

If we want to link to an external website we need to use the HTTPS protocol, whereas if we want to go to another page on the File Protocol (another page in our own site) we would just use something like page2.html

<!-- HTTPS Protocol -->
<a href="https://google.com">Google</a>
<!-- File Protocol -->
<a href="pagetwo.html">Page 2</a>

Recreate Webpage Assignment

Introduction to JavaScript

Unit Objectives

Objective 1. Evaluate JavaScript using the developer console

Objective 2. List the 5 JavaScript primitives

Objective 3. Define variables with the var keyword

Objective 4. Write code using console.log, alert, and prompt


The JavaScript Console

We can write some simple JavaScript code or tests in the Chrome Developer Tools JavaScript Console. You don't write full applications in this console but it is helpful for small blocks of code or testing things.


Primitives

Objectives

  • Introduce the 5 primitive data types
  • Work with numbers and numeric operators
  • Work with strings and common string methods

5 Primitive Datatypes

//Numbers
4;
9.3 - 10;
//-10
//Strings
("Hello World");
("43");
//Booleans
true;
false;
//null and undefined
null;
undefined;

Numbers

//Numbers
4;
9.3 - 10;
//We can do some math
4 + 10; //14
1 / 5; //0.2
//Modulo - remainder operator
10 % 3; //1
24 % 2; //0
15 % 11; //4

Strings

//Single or Double quotes OK
"hello world";
"hello world";
//Concatenation
"charlie" + "brown"; //"charliebrown"
//Escape Characters start with "\"
('Singin "Do wah diddy, diddy, dum diddy do" ');
("This is a backslash: \\");
//Strings have a length property
"hello world".length; //11
//Access individual characters using [] and an index
"hello"[0]; //"h"
"hello"[4]; //"o"

Primitives Exercises

Quick Exercises

Evaluate the following statements

//1.
100 % 3;
//2.
("blah" + "blah")[6];
//3.
"hello".length % "hi\\".length;

Variables

A variable is simply a data storage container where we can store some data.


Null and Undefined

Variables that are declared but not initialized are undefined. Such as var name;.

Null is explicitly nothing. Such as var job = null


Useful Built-In Methods

Three useful JavaScript methods are alert, prompt, and console.log. These methods are very useful for beginning learning and testing JavaScript code.

alert() is a method that displays an alert in the browser. Alert parameters can include strings, numbers, math, variables, etc...

console.log is less intrusive than an alert. It simply prints what we tell it to in the JavaScript in the developer tools console.

prompt is similar to alert except instead of displaying some data, it will give the user an option to enter their own data. We can tie data from alerts into variables or other equations.


Writing JavaScript in a Separate File

The best way to write JavaScript code is to include it in a separate .js file. This file can then be included in our HTML with a script src= tag. Once the script is linked in our HTML it will run when the page is loaded, the hierarchy also matters in how quickly it is executed.


JS Stalker Exercise

Variables, Strings, Prompt, and Console.log

  • Ask for the users first name
  • Ask for the users last name
  • Ask for the users age
  • Print out the users full name in a sentence
  • Print out the users age in a sentence

Solution

let firstName = prompt("What's Your First Name?");
let lastName = prompt("What's Your Last Name?");
let age = prompt("What's Your Age?");
let fullName = firstName + " " + lastName;
alert("Your Full Name Is " + fullName);
alert("And Your Age Is " + age);
console.log("Your Full Name Is " + fullName);
console.log("And Your Age Is " + age);

Age Calculator Exercise

Ask the user how old they are in a prompt, then tell them how many days that is (Estimate).

Solution:

let inputAge = prompt("How old are you?");
let calcAge = inputAge * 365.25;
alert(inputAge + " years is roughly " + calcAge + "days");

JavaScript Basics: Control Flow

Unit Objectives

Objectives:

  • Evaluate complex logical expressions
  • Write 3-part JS conditional statements
  • Write JS while loops and for loops
  • Translate between while and for loops

Boolean Logic

Boolean Logic:

  • Everything starts with the idea that a statement is either True or False.
  • Then we can combine those initial statements to create more complex statements that also evaluate to True or False.
// == vs ===
let x = 99;
x == "99"; // True;
x === "99"; // False;

Comparison Operators


Logical Operators

Logical Operators

The && logical operator requires both sides to be true.

The || logical operator requires only one side to be true.

The ! logical operator simply flips the value of whatever we are evaluating. If there's a statement that is false, and we add !, then it becomes true.


Conditionals

There are 3 key words that allow us to use conditionals. They are if, else if, and else.

A real world example could look something like this... "If you are younger than 18 you cannot enter the venue. If you are between 18 and 21 you can enter but cannot drink. Otherwise you can enter and drink."

if takes a single argument and if the argument returns true then the code inside can run, otherwise the code doesn't run.

else if runs after an if statement if the if statement is false.

else happens as a last resort, after the else and else if. else is different than the other 2 is that we don't have a parenthesis where we put a conditional, we simply write code because it's already a last ditch resort.

Exercises: If age is negative, print an error message. If age is 21, print "happy 21st birthday". If age is odd, print "your age is odd!". Super Bonus: if age is a perfect square, print "perfect square!".

Solution:

const age = prompt("What's your age?");
if (age < 0) {
console.log("Error");
}
if (age == 21) {
console.log("Happy 21st Birthday!");
}
if (age % 2 == 1) {
console.log("Your age is odd!");
}
if (age % age == 0) {
console.log("Perfect Square!");
}

Guessing Game Code Along

Ask a user for a number and if the number is too high or too low, tell them, and if they get it right then we tell them that we got it right.

Solution:

let secretNumber = 4;
let guess = Number(prompt("Guess a number"));
if (guess === secretNumber) {
alert("You got it right!");
} else if (guess > secretNumber) {
alert("Too high!");
} else {
alert("Too low!");
}

Introduction to Loops

Objectives:

  • Understand the purpose of loops
  • Define "DRY" code
  • Write simple while loops

DRY: Don't Repeat Yourself We want to keep our code as DRY as possible. It saves us a lot of time and makes our code cleaner.

While Loops are very similar to an if statement, except it repeats a given code block instead of just running it once.

let count = 1;
while (count < 6) {
console.log("Count is: " + count);
count++;
}
// Count is: 1
// Count is: 2
// Count is: 3
// Count is: 4
// Count is: 5

Infinite Loops occur when the terminating condition in a loop is never true.


3 While Loop Exercises

Exercise 1:

var num = 1;
while (num <= 10) {
console.log(num);
num += 2;
}
// 1 3 5 7 9

Exercise 2:

var num = 1;
while (num <= 20) {
if (num % 4 === 0) {
console.log(num);
}
num++;
}
// 4 8 12 16 20

Exercise 3:

var num = 100;
while (num < 150) {
console.log(num + 1);
num--;
}
// Infinite Loop

While Loops Problem Set

Solution:

console.log("Print all numbers between -10 and 19");
let numberOne = -10;
while (numberOne < 20) {
console.log(numberOne);
numberOne++;
}
console.log("Print all even numbers between 10 and 40");
let numberTwo = 10;
while (numberTwo < 42) {
if (numberTwo % 2 === 0) {
console.log(numberTwo);
}
numberTwo++;
}
console.log("Print all odd numbers between 300 and 333");
let numberThree = 300;
while (numberThree < 335) {
if (numberThree % 2 === 1) {
console.log(numberThree);
}
numberThree++;
}
console.log("Print all numbers divisible by 5 AND 3 between 5 and 50");
let numberFour = 5;
while (numberFour < 50) {
if (numberFour % 3 === 0 && numberFour % 5 === 0) {
console.log(numberFour);
}
numberFour++;
}

Annoy-O-Matic Code Along

The Annoy-O-Matic did not work for me, maybe something to do with using let instead of var. Here is Colts solution

let answer = prompt("Are we there yet?");
while (answer.indexOf("yes") === -1) {
let answer = prompt("Are we there yet?");
}
alert("Yay we made it!");

Intro to For Loops

Objectives:

  • Understand the purpose of for loops
  • Write valid for loops
  • Compare and contrast while loops and for loops
for (init; condition; step) {
// Run Code
}

While vs For


For Loops Quick Exercise

Exercise 1:

for (var i = 0; i < 16; i += 8) {
console.log(i);
}
// 0
// 8

Exercise 2:

var str = "ahceclwlxo";
for (var i = 1; i < str.length; i += 2) {
console.log(str[i]);
}
// h
// e
// l
// l
// o

Loops Problem Set

Print all numbers between -10 and 19 Print all even numbers between 10 and 40 Print all odd numbers between 300 and 333 Print all numbers divisible by 5 AND 3 between 5 and 50

Solution:

console.log("Print all numbers between -10 and 19");
for (problemOne = -10; problemOne < 20; problemOne += 1) {
console.log(problemOne);
}
console.log("Print all even numbers between 10 and 40");
for (problemTwo = 10; problemTwo < 42; problemTwo += 1) {
if (problemTwo % 2 === 0) {
console.log(problemTwo);
}
}
console.log("Print all odd numbers between 300 and 333");
for (problemThree = 300; problemThree < 335; problemThree += 1) {
if (problemThree % 2 === 1) {
console.log(problemThree);
}
}
console.log("Print all numbers divisible by 5 AND 3 between 5 and 50");
for (problemFour = 5; problemFour < 50; problemFour += 1) {
if (problemFour % 3 === 0 && problemFour % 5 === 0) {
console.log(problemFour);
}
}

Loops Problem Set: Solution

console.log("Print all numbers between -10 and 19");
for (problemOne = -10; problemOne < 20; problemOne += 1) {
console.log(problemOne);
}
console.log("Print all even numbers between 10 and 40");
for (problemTwo = 10; problemTwo < 42; problemTwo += 1) {
if (problemTwo % 2 === 0) {
console.log(problemTwo);
}
}
console.log("Print all odd numbers between 300 and 333");
for (problemThree = 300; problemThree < 335; problemThree += 1) {
if (problemThree % 2 === 1) {
console.log(problemThree);
}
}
console.log("Print all numbers divisible by 5 AND 3 between 5 and 50");
for (problemFour = 5; problemFour < 50; problemFour += 1) {
if (problemFour % 3 === 0 && problemFour % 5 === 0) {
console.log(problemFour);
}
}

JavaScript Basics: Functions

Unit Objectives

  1. Write function declarations and function expressions.
  2. Explain the difference between console.log and return.
  3. Define functions that take multiple arguments.

Introduction to Functions

Objectives:

  • Understand why we use functions
  • Define a function without arguments
  • Define a function with arguments
  • Return a value from a function

Functions let us wrap bits of code up into reusable packages. They are one of the building blocks of JavaScript.

Declare a function first. Then call it.

function consoleHelloWorld() {
console.log("Hello World!");
}
consoleHelloWorld();
// Hello World!

In order to run the function, we need to add the parenthesis. Without the parenthesis, all that is happening is we're referencing the function.


Arguments

Arguments are how we can give our function some inputs. Functions can have as many arguments as needed.

function square(num) {
console.log(num * num);
}
square(4); // 16

Another example:

function sayHello(name) {
console.log(`Hi there ${name}`);
}
sayHello("Nick");

Functions can have multiple arguments and string concatenation can help display these values.

function area(length, width) {
console.log(`The area is ${length * width}`);
}
area(5, 4);

The Return Keyword

Often we want a function to send back an output value.

Every function returns something. If we don't tell it explicitly what to return, it will return undefined.

result can also be used with variables.

let result = functionName(param)

The Return Keyword

The return keyword stops execution of a function. As soon as the return value is activated, the function stops its execution and provides the value.

There are 2 ways to write functions. There's function declaration and there's function expression.

Function Declaration vs Function Expression


Functions Quiz

What does the following code return?

function test(x, y) {
return y - x;
}
test(10, 40);
// 30
function test(x) {
return x * 2;
console.log(x);
return x / 2;
}
test(40);
// 80

Function Problem Set

Write a function isEven() which takes a single numeric argument and returns true if the number is even, and false otherwise.

function isEven(num) {
return num % 2 === 0;
}
isEven(41);

Write a function factorial() which takes a single numeric argument and returns the factorial of that number.

function factorial(num) {
var result = 1;
for (var i = 1; i <= num; i++) {
result *= i;
}
return result;
}
factorial(10);

Write a function kebabToSnake() which takes a single kebab-cased string argument and returns the snake_cased version.

function kebabToSnake(string) {
let str = string.replace(/-/g, "_");
return str;
}
kebabToSnake("hi-there");

Scope Code Along

There are different scopes available to us. Global scope refers to what is declared outside of any functions, and local scope would be a variable that is declared inside of a function. If a variable is declared in the global scope, it is still accessible in the local scope, but local scope is not available in the global scope.

If a variable is declared in the global scope, but then it is changed in the local scope, that has the power to change the variable from the global scope. This is only true if the local scope is referencing the already made variable (without let)but if let is used, then it makes a new variable that is tied to that scope.


Scope Quiz

Scope is the context that code is executed in.

let num = 8;
function doMath() {
num += 1;
if (num % 5 == 0) {
return true;
} else {
return false;
}
}
num += 1;
doMath();
// True

QUESTION

function scopeOne() {
let name = "nick";
console.log(name);
scopeTwo();
}
function scopeTwo() {
console.log(name);
}
scopeOne();

Higher Order Functions Code Along

What if we wanted to run a function every set amount of time without having to repeatedly reference it. We could use the setInterval() function. This function takes 2 arguments, the first one being the name of the function to call, and the second being the time between calls. To stop setInterval, we can call another function called clearInterval() and pass in the number that setInterval() gave us.

A higher order function is a function that takes or returns a function as an argument.

An anonymous function is where you don't have a function written, but you write one in the parameter of another function. setInterval(function(){console.log("Anonymous Function!")}, 2000)

function sing() {
console.log("twinkle twinkle");
console.log("how i wonder...");
}
setInterval(sing, 1000);

JavaScript Basics: Arrays

Unit Objectives

An array lets us store ordered groups of data and we can put anything we want in there.

Objective 1: Define and add data to arrays Objective 2: Utilize built-in array methods Exercise: Console Todo List


Introduction to Arrays

Objectives:

  • Understand arrays conceptually
  • Write code using JavaScript arrays

Suppose I wanted to model a group of friends. Instead of writing a variable for each friends name, I could write an array that contains all the names.

Arrays are indexed starting at 0. Every slot has a corresponding number.

To simply update the array using bracket notation, just reference the position you're trying to update or add to. colors[3] = "green"


Arrays Methods

Arrays come with a few built-in methods that make our life easier. We're going to cover:

  • push / pop
  • shift / unshift
  • indexOf
  • slice

Use push to add to the end of an array. Use pop to remove the last item in an array.

Use unshift to add to the front of an array. Use shift to remove the first item in an array.

Use indexOf to find the index of an item in an array.

Use slice to copy parts of an array. This does not alter the original array that you're slicing from. To copy an entire array just use slice with no arguments.


Array Quiz

let numbers = [22, 67, 33, 96, 88];
console.log(numbers[numbers.length]);
// undefined

The reason we get undefined in the problem above is because in the brackets we would be asking for numbers[5] because the length property counts from 1 but arrays are indexed starting at 0 so there is no array with the index of 5 thus returning undefined.

let friendGroups = [
["Harry", "Ron", "Hermione"],
[("Malfoy", "Crabbe", "Goyle")],
["Mooney", "Wormtail", "Prongs"],
];
console.log(friendGroups[2][0]);
// Mooney

Note about Todo List Code Along

Hi All,

In the following lecture you will be using the prompt function in your JavaScript to display messages and accept input from the user.

Chrome browser behaves a little strangely when using alert, prompt, or confirm functions. It doesn't display the HTML on the page until after the popup has been closed. This is problematic since our HTML contains instructions for the user to be able to use the app we're building.

You can avoid this by wrapping your JS code in the following setTimeout function:

window.setTimeout(function () {
// put all of your JS code from the lecture here
}, 500);

This gives the HTML a half second to load before running the JS, which circumvents the issue of the prompt function blocking the HTML from loading right away.

This is not something you would have to deal with in the real world as prompt, alert, and confirm functions are almost never used and when they are it's typically not on page load.

You'll also learn jQuery in latter sections which has a cool $('document').ready() function that you could use in place of the window.setTimeout workaround mentioned above.


Todo List Code Along Part 1

Here's the logic for the command line todo list using prompt()

let todos = [];
let input = prompt("What would you like to do?");
while (input !== "quit") {
if (input === "list") {
console.log(todos);
} else if (input === "new") {
let newTodo = prompt("Enter new todo!");
todos.push(newTodo);
}
input = prompt("What would you like to do?");
}
console.log("Ok, you quit");

Array Iteration

Objectives:

  • Use a for loop to iterate over an array
  • Use forEach to iterate over an array
  • Compare and contrast for loops and forEach

For Loop: To loop over an array using a for loop, we need to make use of the array's length property.

let colors = ["red", "orange", "yellow", "green"];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}

forEach: JavaScript provides an easy built-in way of iterating over an array.

arrayName.forEach(function () {
console.log("Inside the forEach");
});
// (4)Inside the forEach

What happens if we pass in a parameter to forEach?

The parameter takes in each item in the array.

arrayName.forEach(function (colors) {
console.log(colors);
});

This would take each item in the array as a color and iterate over each one of them.


Quick Array Iteration Challenge

What does the following code print out?

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let colors = ["red", "orange", "yellow", "green"];
numbers.forEach(function (color) {
if (color % 3 === 0) {
console.log(color);
}
});
// 3 6 9

Note about Todo List Code Along Part 2

Colt will be using the Array.forEach function in the next video. This note to provides further information about .forEach and how it works. Also, this thread provides even further clarification for anyone still struggling with the concepts explained below.

.forEach takes a callback function, that callback function is expected to have at least 1, but up to 3, arguments. This is how .forEach was designed.

The arguments are in a specific order:

  • The first one represents each element in the array (per loop iteration) that .forEach was called on.
  • The second represents the index of said element.
  • The third represents the array that .forEach was called on (it will be the same for every iteration of the loop).

You have a couple options when calling .forEach on an array:

You can pass in an anonymous function:

[1, 2, 3].forEach(function (el, i, arr) {
console.log(el, i, arr);
});

Or you can pass in a pre-written, named function.

function logNums(el, i, arr) {
console.log(el, i, arr);
}
[1, 2, 3].forEach(logNums);

Notice how in the second example we don't invoke logNums when passing it into .forEach? We simply pass in the function name. We don't need to invoke the logNums function, .forEach does that for us. In fact, it invokes the function multiple times, once for every element inside of the array.

I hope that helped clear some things up, please see this thread or post a question in the Q&A if you're unsure of anything that I've shared above.


Todo List Code Along Part 2

We made use of for each and function calling inside of conditional calls.

let todos = [];
let input = prompt("What would you like to do?");
while (input !== "quit") {
listTodos();
if (input === "new") {
addTodo();
} else if (input === "delete") {
deleteTodo();
}
input = prompt("What would you like to do?");
}
console.log("Ok, you quit");
function listTodos() {
todos.forEach(function (todo, index) {
console.log("----------");
console.log(index + ": " + todo);
});
}
function addTodo() {
let newTodo = prompt("Enter new todo!");
todos.push(newTodo);
console.log("Added Todo");
}
function deleteTodo() {
let index = prompt("Enter index of todo to be deleted");
todos.splice(index, 1);
console.log("Deleted Todo");
}

Array Problem Set

Write a function printReverse() that takes an array as an argument and prints out the elements in the array in reverse order (don't actually reverse the array itself).

function printReverse(array) {
for (var i = array.length - 1; i >= 0; i--) {
console.log(array[i]);
}
}
printReverse([0, 2, 4, 6, 8, 10]);

Write a function isUniform() which takes an array as an argument and returns true if all elements in the array are identical.

function isUniform(array) {
let first = array[0];
for (let i = 0; i < array.length; i++) {
if (array[i] !== first) {
return false;
}
}
return true;
}
console.log(isUniform([5, 5, 5, 5, 5]));

Write a function sumArray() that accepts an array of numbers and returns the sum of all numbers in the array.

function sumArray(array) {
let total = 0;
array.forEach(function (element) {
total += element;
});
return total;
}
console.log(sumArray([56, 345, 2, 3, 54, 7, 23, 2, 635]));

Write a function max() that accepts an array of numbers and returns the maximum number in the array.

function max(array) {
let max = array[0];
for (var i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
console.log(max([5, 3456, 234, 456, 3, 534, 5, 234, 254, 3880, 34, 534]));

Optional: Building Our Own forEach

Come back to this at the end of the course.


JavaScript Basics: Objects

Introduction to Objects

Objectives:

  • Understand objects conceptually
  • Write code using JS objects

The perfect use case for an object vs an array is something like information about a person... the city they live in, their age, their name, etc. This is all information that doesn't necessarily need to be in order and if we put it in an object we can access the data more easily.

There are 2 ways to get data out of objects. Bracket notation looks like console.log(person["name"]); Dot notation looks like console.log(person.name);

There are a few differences between these retrieval methods. You cannot use dot notation if the property starts with a number. You cannot use dot notation for property names with spaces.

To update data, we can use either the dot or square bracket notation. person.city = "Phoenix" will assign the value of Phoenix to the city property in the person object.

Objects can hold all sorts of data.


Comparing Objects and Arrays

Arrays are used to store ordered lists of data. Every item is bound to an index that we can refer to.

Objects have no particular order. Key value pairs are what make objects different. Think of it like a dictionary, there's lots of key value pairs.

// Array
let dogs = ["Sadie", "Jetta", "Scout"];
// Object
let dogs = {
name: "Sadie",
breed: "Mutt",
};

Now how do we access data from each of these?

// Array
let dogs = ["Sadie", "Jetta", "Scout"];
dogs[1]; // Jetta
// Object
let dogs = {
name: "Sadie",
breed: "Mutt",
};
dogs.name; // Sadie
dogs["name"]; // Sadie

An array is just a special type of object.

How do we add new data into each of these?

// Array
let dogs = ["Sadie", "Jetta", "Scout"];
dogs.push("Walter");
// Object
let dogs = {
name: "Sadie",
breed: "Mutt",
};
dogs.age = 2;

Finally, how do update data in each of these?

// Array
dogs[1] = "Barky";
// Object
dogs.breed = "Wolf Dog";

Nested Objects and Arrays

let posts = [
{
title: "Care are mediocre",
author: "Colt Steele",
comments: ["Wow"]
},
{
title: "Cats are actually awesome",
author: "Cat Lover"
comments: ["An array of comments!"]
}
];

Objects Quiz

Exercise 1:

let someObject = {};
// Which of the following are valid:
someObject._name = "Noah"; // Valid
someObject.age = 6; // Valid
let prop = "color"; // Valid
someObject[prop] = "red"; // Valid
someObject.123 = true;

Exercise 2:

let someObject = {
friends: [{ name: "Harry" }, { name: "James" }, { name: "Liam" }],
color: "baby blue",
isEvil: true,
};
// Write code that retrieves Harry
someObject.friends[0].name;

Movie Database Exercise

We were asked to write an array containing objects of movies with properties.

let movies = [
{
title: "Unbroken",
rating: 5,
hasWatched: true,
},
{
title: "Frozen 2",
rating: 4.6,
hasWatched: false,
},
{
title: "Red Dawn",
rating: 4.2,
hasWatched: true,
},
{
title: "Uncut Gems",
rating: 4.7,
hasWatched: false,
},
];
for (i = 0; i < movies.length; i++) {
if (movies[i].hasWatched === true) {
console.log(
`You have watched "${movies[i].title}" - ${movies[i].rating} stars`
);
} else if (movies[i].hasWatched === false) {
console.log(
`You have not watched "${movies[i].title}" - ${movies[i].rating} stars`
);
}
}

Adding Methods to Objects

A method is just a function that is a property inside of an object.

If we write a function as a property on an object, we cannot reference it like we did before. We have to use dot notation to call it, maybe something like this. object.add(5,6)


The Keyword This

For now, the keyword this refers to the object in which this is contained.

const test = {
prop: 42,
func: function () {
return this.prop;
},
};
console.log(test.func());
// expected output: 42

DOM Manipulation

Introduction to the DOM

Objectives:

  • Define what the DOM is
  • Understand why DOM Manipulation is awesome
  • List a few examples of sites that use JS to manipulate the DOM
  • Understand the SELECT, then MANIPULATE workflow

Why should you care? A few examples:

  • Games
  • Scrolling Effects
  • Dropdown Menus
  • Form Validations
  • Interactivity
  • Animations
  • Every awesome site ever

Defining the DOM

Document Object Model (DOM) is the interface between your JavaScript and HTML + CSS.

It's really a giant object containing all the HTML and other things behind the scenes that make up the webpages we see.

To see this whole object we can type console.dir(console).

![DOM](Add the link)


Select and Manipulate

First we need to select the element we're going to manipulate. Then we can manipulate using built in JS manipulation features.

let h1 = document.querySelector("h1");
h1.style.color = "pink";

Another example is to change the background color from white to blue every second.

let body = document.querySelector("body");
let isBlue = false;
setInterval(function () {
if (isBlue) {
body.style.background = "white";
} else {
body.style.background = "#3498db";
}
isBlue = !isBlue;
}, 1000);

Important Selector Methods

All of the selectors we need to use to manipulate HTML live inside of the document object. The 4 main document selectors we have are body, head, links, and URL.

The document comes with a bunch of methods for selecting elements. We're going to learn about the following 5:

  • document.getElementById()
  • document.getElementsByClassName()
  • document.getElementsByTagName()
  • document.querySelector()
  • document.querySelectorAll()

getElementById() Takes a string argument and returns the one element with a matching ID

getElementsByClassName() Takes a string argument and returns a list of elements that have a matching class

getElementsByTagName() Returns a list of all elements of a given tag name, like <li> or <h1>

querySelector() Returns the first element that matches a given CSS-style selector

querySelectorAll() Returns a list of elements that match a given CSS-style selector


Selector Exercise

Come up with 4 different ways to select the first <p> tag.

document.getElementById("first");
document.getElementsByClassName("special")[0];
document.querySelector("p");
document.querySelector("p.special");
document.querySelector(".special");

There are plenty of other ways we can do this.


Manipulating Style

DOM Manipulation. We're going to cover different ways of:

  • Changing an element's style
  • Adding / removing classes
  • Changing the content of a tag
  • Changing attributes (src, href, etc)

The style property is one way to manipulate an element's style.

const button = document.querySelector("#button");
button.style.border = "10px solid red";

There is a style property available for every CSS element.

Instead of calling .style multiple times and clustering our JavaScript code, we can change the class name on the element and write different class options in our CSS.

There are a few useful classList properties we can use to change our CSS from our JS. We have classList.add, classList.remove, and classList.toggle, which will either add or remove a class based on whether or not the element already has the class applied. Could be used for a dark mode stylesheet toggle.


Manipulating Text and Content

textContent: Returns a string of all the text contained in a given element. Can be used to either view the text or manipulate the text inside a property.

let tag = document.querySelector("#tag");
tag.textContent; // "Hello World"
tag.textContent = "Hello Nick";

There is also a method called innerText which is very similar, however there are some differences.

innerText returns the visible text contained in a node, while textContent returns the full text. For example, on the following HTML <span>Hello <span style="display: none;">World</span></span>, innerText will return 'Hello', while textContent will return 'Hello World'. Additionally, innerText is defined only for HTMLElement objects, while textContent is defined for all Node objects.

Due to these differences, it is probably best to use textContent for a more complete text manipulation experience.

innerHTML: Similar to textContent, except it returns a string of all the HTML contained in a given element.

let tag = document.querySelector("#tag");
tag.innerHTML = "This is a <strong>tag</strong>";

Manipulating Attributes

Use getAttribute() and setAttribute() to read and write attributes like src or href.

We can change attributes by calling setAttribute() and changing whatever attribute we need.

let img = document.querySelector("img");
img.setAttribute("src", "newImage.png");

Playing With Google Code Along

If we wanted to do something like grab all the a tags, we could grab all of them with something like querySelectorAll(), then we can run a for loop and change all of the a tags by looping through and assigning a style to each of them.


Advanced DOM Manipulation

Introduction to Events

Events are everywhere:

  • Clicking on a button
  • Hovering over a link
  • Dragging and dropping
  • Pressing the Enter key

The Process: We select an element and then add an event listener.

  • "Listen for a click on this <button>"
  • "Listen for a hover event on the <h1>"
  • "Listen for a keypress event on text input"

The Syntax: To add a listener, we use a method called addEventListener(type, functionCall)

const button = document.querySelector("button");
button.addEventListener("click", function () {
console.log("Someone clicked the button!");
});

If we want to refer to a specific element that we're interacting with, say inside of an event listener, the keyword this refers to the element that was interacted.

Event listeners can be added without anonymous functions, we can simply write our function in the global scope and then pass the name of the function into the callback of the event listener.


Note about Introduction to Events

Hi Everyone! If you're wondering why you get an error when trying to use lis[i] instead of this then check out this quick video that explains the difference between the two.

arrayVar[i] vs this


Color Toggle Exercise

Toggle the body's background color between white and a color of your choice when a button is clicked.

const button = document.querySelector("button");
button.addEventListener("click", () => document.body.classList.toggle("dark"));

This will select a button on the page and toggle the classes on the body when the button is clicked.


Score Keeper Project

const p1 = document.querySelector("#p1");
const p2 = document.querySelector("#p2");
const reset = document.querySelector("#reset");
const h1 = document.querySelector("h1");
const p1Display = document.querySelector("#p1Display");
const p2Display = document.querySelector("#p2Display");
const input = document.querySelector("input");
const p = document.querySelector("#pSpan");
let p1Score = 0;
let p2Score = 0;
let gameOver = false;
let winningScore = 5;
p1.addEventListener("click", () => {
if (!gameOver) {
p1Score++;
if (p1Score === winningScore) {
p1Display.classList.add("winner");
gameOver = true;
}
p1Display.textContent = p1Score;
}
});
p2.addEventListener("click", () => {
if (!gameOver) {
p2Score++;
if (p2Score === winningScore) {
p2Display.classList.add("winner");
gameOver = true;
}
p2Display.textContent = p2Score;
}
});
reset.addEventListener("click", () => {
resetFunc();
});
input.addEventListener("change", () => {
p.textContent = input.value;
winningScore = Number(input.value);
resetFunc();
});
const resetFunc = () => {
p1Score = 0;
p2Score = 0;
p1Display.textContent = 0;
p2Display.textContent = 0;
p1Display.classList.remove("winner");
p2Display.classList.remove("winner");
gameOver = false;
};

Other Types of Events: Todo List

We worked with some of the many JavaScript events available to use. The ones we worked with were mouseover and mouseout.

let li = document.querySelectorAll("li");
for (let i = 0; i < li.length; i++) {
li[i].addEventListener("mouseover", () => {
li[i].classList.add("selected");
});
li[i].addEventListener("mouseout", () => {
li[i].classList.remove("selected");
});
li[i].addEventListener("click", () => {
li[i].classList.toggle("done");
});
}

We toggled and added and removed styles based on what the mouse or click listeners were doing.

MDN Event Reference


Counting Events Exercise

const events = document.querySelectorAll("td > code");

Color Game Project

Creating the Color Game Pt: 1

We're going to be creating a color guessing game. How it works is there are 6 random colors when we load up the page, and one of the colors is listed at the top. Our job is to pick which color is the one that is listed at the top.


Creating the Color Game Pt: 2

We set up a grid that has 6 squares and added individual styling to them and then set up an event listener that compares the color that we clicked on to the color that is chosen and if they are the same it will alert us saying correct.


Creating the Color Game Pt: 3

This episode, we set up a function that will loop over the array and pick a random element using a random index generated from using Math.random and Math.floor.


Creating the Color Game Pt: 4

In this video, we added a feature that will randomly pick a color based on RGB color standards for us.

function randomColor() {
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
return `rgb(${r}, ${g}, ${b})`;
}

Creating the Color Game Pt: 5

In this lesson, we added a feature that allows us to have a reset button.

reset.addEventListener("click", () => {
colors = generateRandomColors(6);
pickedColor = pickColor();
colorDisplay.textContent = pickedColor;
for (let i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = colors[i];
}
h1.style.backgroundColor = "#232323";
});

Creating the Color Game Pt: 6

In this module we added 2 buttons that let us switch between hard mode and easy mode and allows us to generate a different amount of color squares based on which mode we're in.


Creating the Color Game Pt: 7

In this section, we added some CSS transitions as well as some other styling features.


Creating the Color Game Pt: 8

In this section, we DRYed our code and moved some things into more compact function calls and smaller event listeners.


Creating the Color Game Pt: 9

In this section, we wrapped most of our code into a general init() function.


Intro to jQuery

What is jQuery?

What is jQuery? jQuery is a DOM manipulation library.

jQuery is simply some code that someone else has written that we include into our code and we can access what we need out of that file.

It comes with a bunch of useful methods to things like:

  • Select Elements
  • Manipulate Elements
  • Create Elements
  • Add Event Listeners
  • Animate Elements
  • Add Effects
  • Make HTTP Requests (AJAX)

Why Use jQuery?

YMNNJQ

Why Use jQuery?

  • Fixes "broken" DOM API
  • Brevity and Clarity
  • Ease of use
  • Cross-Browser Support
  • AJAX
  • Lot's of people use jQuery!

Why Not Use jQuery?

  • The DOM API is no longer "broken"
  • It doesn't do anything you can't do on your own
  • It's an unnecessary dependency
  • Performance
  • Lot's of people are moving away from jQuery!

Either way, it's worth knowing.


Including jQuery

Download jQuery and link to it locally: src="jQuery.js" OR Link to a CDN (a hosted copy): src="https://jQuery.min.js

If we're going to download jQuery and include it into our source code, we can add it into a lib folder, this is somewhere where we keep our library files.


Selecting with jQuery

Objectives:

  • Select elements with \$()
  • Use .css() to style elements

Selecting with jQuery: $("selectorGoesHere"). Selecting with jQuery is very similar to querySelectorAll, in that we provide a CSS style selector and jQuery will return all matching elements.

// Select all image tags
$("img");
// Select all elements with the class "sale"
$(".sale");
// Select all elements with th eid "bonus"
$("#bonus");
// Select all a tags inside of li's
$("li a");

Manipulating Style: The .css() method is jQuery's interface to styling. $("selector").css(property, value) $("h1").css("color", "yellow");

We can also pass in an object with styles

let styles = {
backgroundColor: "pink",
fontWeight: "bold",
};
$(".classes").css(styles);

Selectors Exercise

Exercise:

  • Correctly include jQuery
  • Select all divs and give them a purple background
  • Select the divs with class "highlight" and make them 200px wide
  • Select the div with the id "third" and give it an orange border
  • Bonus: Select the first div only and change its font color to pink
<div>Div 1</div>
<div class="highlight">Div 2</div>
<div id="third">Div 3</div>
<div class="highlight">Div 4</div>
$("div").css("backgroundColor", "purple");
$("div.highlight").css("width", "200px");
$("#third").css("border", "2px solid orange");
$("div:nth-of-type(1)").css("color", "pink");

Text and HTML

Objectives:

  • val()
  • text()
  • attr()
  • html()
  • addClass()
  • removeClass()
  • toggleClass()

.text() is very similar to textContent from vanilla JS. It will return all the text inside the container on which it is called. We can also use it to set text inside of elements.

html() is very similar to innerHTML from vanilla JS. It will return the HTML from the element on which it is called, but we can also use it to set some new HTML.

We can't use .text to set HTML it will simply treat anything that is passed inside as a string. This is a good option for something like user inputs that we then take the value from. If the user inputs some JavaScript into the input form we could have security vulnerabilities.


Attr and Val

.attr() allows us to either set or retrieve an attribute.

$("img").attr("src", "https://image.png");

.val() is the same thing as .value in vanilla JS, it simply gets the input value and returns a string. We can also use it to add text to the input, or an empty string that acts as a sort of reset functionality.


Manipulating Classes

Manipulating classes with jQuery is very similar to manipulating with vanilla classList.add etc in JS.

$("h1").addClass(".done");
$("h1").removeClass(".remove");
$("h1").toggleClass(".toggle");

Advanced jQuery

jQuery Events: Click

Objectives:

  • click()
  • keypress()
  • on()

click(): jQuery's click() method is a quick and easy way to add a click listener to elements.

$("#submit").click(function () {
console.log("Another click");
});

jQuery has its own this inside of $(this).


jQuery Events: Keypress

Keypress demo:

$("target").keypress(function () {
console.log("Key was pressed!");
});

jQuery Events: On

jQuery's on() works similarly to addEventListener(). It lets you specify the type of event to listen for. It has some more advanced features compared to addEventListener() where with on() you can listen for things like double clicks, or on-drag, or other things.

It's not just for click events. on() supports all types of events.

// Double click event
$("button").on("dbclick", () => {
console.log("Double clicked!");
});

Why use on()? In most cases, click() and on("click") will both get the job done. However, there is one key difference:

  • click() only adds listeners for existing elements
  • on() will add listeners for all potential future elements
  • This will all make sense in the next video

jQuery Effects

jQuery allows us to easily add some CSS type effects with just one line of jQuery.

$("div").fadeOut(200, () => {
console.log("This is a callback for after the fade finishes");
$(this).remove();
});

This doesn't delete or remove our elements from the page it simply hides them, unless we call remove() in the fade callback function.

We also have fadeIn() which works just like fadeOut().

fadeToggle() works like classList.toggle where it will either fade in our fade out based on what effect is currently applied to the element.

slide is another animation method which will animate the height and display of an element. we can use slideToggle, slideUp, slideIn.


Todo List Projects

Intro to the Todo List App

In this todo project, well get more practice with jQuery and CSS.

  • on()

  • keypress()

  • Fade and slide

  • Selecting

  • Margin

  • Padding

  • Float

  • Fonts

We'll also learn some new things, including...

  • A better folder structure

  • .parent()

  • .append()

  • Creating elements

  • Event delegation

  • Font-awesome

  • Box-shadow

  • Transition

  • Gradients


Todo List: Folder Structure

In this video we just set up a static folder containing code for our js and css as well as a lib folder that contains code from libraries.


Todo List: Basic HTML

In this video we added a container div as well as a ul with some li's and a span with an x for when we need to delete elements.


Todo List: Marking Completion

In this video, we went over how to add a line-through and turn our text gray when we click on a todo. To do this we can simply use a CSS class toggle method, I did this with vanilla JS but Colt is completing this with jQuery.


Todo List: Deleting Todos

In this video, we went over the jQuery methods available to delete an li element when we clicked on the X span. I did this with the following vanilla JS.

spans.forEach((span) => {
span.addEventListener("click", () => {
span.parentElement.remove();
});
});

Todo List: Creating Todos

In this video we focused on being able to create different todos and have the ability to mark the new items we create as completed.


Todo List: Styling Pt. 1

In this video, we added custom fonts and background colors as well as styling the li's.


Todo List: Styling Pt. 2

In this video, we added a liner gradient as our background that will scale with the viewport size.

We also added the delete icon and hover styles so that it increases in width upon hovering.


Todo List: Toggling the Form

In this section, we were able to add a toggle to our input form so that when we click the plus button the form will toggle in or out. We also sorted our CSS by specificity.


OPTIONAL Project: Patatap Clone

Project Intro

We are going to be making a project that incorporates 2 libraries, the first being paper.js and the second being howler.js. We are going to be using paper.js for our graphics and howler for our sounds. The project is a patatap clone, this gives us a blank page but when we type a key, we get a interesting sound and visual animation and each key gets its own sound and color.


Paper.js Intro

In this video we look at the paper.js library and how it interacts with the HTML Canvas by drawing shapes on based on our paperscript code.


Paper.js Exercise

In order to draw a circle every 100 pixels we need to use a for loop that will draw a circle and change the pixel alignment slightly on every loop.

for (var x = 0; x < 1000; x += 100) {
for (var y = 0; y < 1000; y += 100) {
new Path.Circle(new Point(x, y), 10).fillColor = "yellow";
}
}

Adding Keypress Events

In this video, we figured out how to find the maximum available screen size to generate random circles on based on keypress.


Paper.js Animations

In this video, we figured out how to have our circles change color and appear randomly on the screen, then change color while the size shrinks to zero.


Adding Howler.js

In this video, we added the sound library howler.js. This will help us add sound files and play them on clicks.


Backend Basics

Introduction to Backend

Intro to Backend

  • Review Internet Basics
  • Static vs Dynamic Sites
  • Stacks / Backend Technologies

When we visit a site, say "http://www.udemy.com/courses", our computer has to figure out the right address.

  • Your query is submitted to your ISP
  • Within your ISP, the DNS takes the Domain name and turns it into an IP address

Once we have the address, we need to actually go there

  • A request is sent to the desired IP address via HTTP
  • Your request finds the fastest path possible to the server with the specified IP address
  • This is not a direct journey. It requires hopping from one server to another until we arrive

Once the server gets our request, it can respond

  • The requested server figures out exactly what we're asking for (/courses)
  • The server builds us the right content, often pulling information from a database
  • The server responds with any combination of HTML, CSS, and JavaScript

Static VS Dynamic If a site is truly dynamic, it will be changing the actual source code underneath because of the response it gets from a database, but if it's static it can appear different but it will have the same underlying code every time we visit. Even something like the color game we built is a static site because the code never changes, it just pulls different values from our color options to change the background and tile colors.

A Generic Stack contains a backend language, a server, a database, and a frontend. A stack for a popular website like Reddit.com, as of awhile ago, looks like this.

  • Backend language = Python / Flask
  • Server = NGINX
  • Databases = PostgreSQL
  • Frontend = Backbone

Our stack will use NodeJS, Express, and MongoDB for the backend and JavaScript for the frontend. Here are some examples of what we can do with our fullstack knowledge.

  • Backend = Check if the user is logged in, figure out what code to send the user
  • Server = Sign up a user, add new post to DB, create new comment
  • Database = Remove post from DB, sort/rank posts, create subreddit, add to newsletter list
  • Frontend = Compile UI based on data from backend

HTTP in Depth

Postman is a tool that lets us visualize our HTTP requests. There are quite a few of HTTP options, but the most common are GET, POST, DELETE. We can also add query options, which are key value pairs into our HTTP request string to alter what data the server is going to send back to us.

We are not altering anything when we make requests, we are just asking for some data and the server is sending it to us.


Backend Workflow Pt. 1

In this video, we looked at an Express server and how our server can return different code based on different URL requests.


Backend Workflow Pt. 2

In this video, we looked at how POST requests work and how we use forms and input fields to submit data.


Introduction to Cloud 9

One advantage to using a cloud-based IDE (Integrated Development Environment) is that every machine is different and when we're installing everything we need for fullstack development, we run into a lot of problems. With a cloud-based IDE, it's set up the same and there are more resources available because it's a unified system.

An alternative to what is commonly offered is Amazon Web Service's Cloud 9 IDE. It is a cloud based IDE that provides a free tier and terminal access with the system running Amazon Linux.


Setting up Cloud 9

This video goes over the basic features that are included in the Cloud9 Online IDE.


The Command Line

Introduction to the Command Line

The terminal/cli allows us to be a lot more powerful and quick with interacting with our computer.


CD and LS

ls will show all of the current files inside of the folder or directory your command was run in.

cd will allow us to change directories and move between files and folders.


Touch and Mkdir

touch allows us to make a new file.

mkdir allows us to make a new directory.


Removing Files and Folders

rm allows us to remove a file.

rm -rf allows us to remove a folder or directory.


Command Line Exercise

  • Make a new folder named "Animals"
mkdir Animals
  • Inside of Animals add 2 directories: AwesomeAnimals and SketchyAnimals
mkdir Animals/AwesomeAnimals
mkdir Animals/SketchyAnimals
  • Inside of AwesomeAnimals add the following files: Capybara.js, ArcticFox.html, and TreeFrog.txt
cd Animals/AwesomeAnimals
touch Capybara.js ArcticFox.html TreeFrog.txt
  • Inside of SketchyAnimals add the following files: BrownRecluse.html and BulletAnt.js
cd ../SketchyAnimals
touch BrownRecluse.html BulletAnt.js
  • Also inside of SketchyAnimals create a Snakes directory.
mkdir Snakes
  • Inside the Snakes directory create the following files: Cobra.css and ReticulatedPython.js
touch Snakes/Cobra.css Snakes/ReticulatedPython.js
  • Remove the BulletAnt.js file
cd ..
rm BulletAnt.js
  • Delete the entire Animal directory
cd
rm -rf Animals

Node JS

Introduction to Node

What is Node and why are we learning it?

Node is simply a way for us to write JavaScript code on the server side of things.

A few reasons that we should learn Node include its popularity, community, performance, JavaScript runtime, package ecosystem, and its asynchronous runtime.


Using Node

Our first experience with Node is using the Node REPL (Read Evaluate Print Loop). This is a terminal operation that allows us to type and execute JavaScript in our console.

We can also use Node to execute our JavaScript files. We do this by typing node fileName.js into the terminal.


Node Echo Exercise

Write a function called echo that takes 2 arguments: a string and a number. It should print out the string, number number of times.

// echo.js
const echo = (phrase, number) => {
for (let i = 0; i < number; i++) {
console.log(phrase);
}
};
echo("Echo Log", 4);
// Echo Log
// Echo Log
// Echo Log
// Echo Log

Node Average Exercise

Take an array of test numbers and return the average score in the array, rounded to the nearest whole number.

const grader = (arr) => {
let result = 0;
arr.forEach((num) => {
result += num;
});
return Math.round(result / arr.length);
};
grader([90, 98, 89, 100, 100, 86, 94]); // 94
grader([40, 65, 77, 82, 80, 54, 73, 63, 95, 49]); // 68

Introduction to NPM

NPM is the package manager that allows us to include other peoples code into our Node scripts.

Since we don't include a script tag into Node, we use NPM to get packages into our app.


Installing NPM Packages

To install npm packages, open a terminal window and type npm install packageName, from there a package.json file will be generated and to include the new package in our code we use require like const packageName = require("packageName").


NPM Faker Exercise

The challenge in this video was to get a package from NPM and generate and print some fake data from the library.

const faker = require("faker");
for (let i = 0; i < 10; i++) {
const name = faker.commerce.productName();
const price = faker.finance.amount();
console.log(`${name}: $${price}`);
}
// Generic Concrete Chicken: $801.86
// Generic Metal Mouse: $89.86
// Incredible Rubber Car: $528.54
// Gorgeous Wooden Mouse: $414.52
// Practical Granite Salad: $313.82
// Unbranded Granite Sausages: $450.15
// Practical Metal Table: $956.65
// Unbranded Plastic Hat: $450.85
// Tasty Cotton Bike: $263.05
// Practical Cotton Chicken: $589.32

Server Side Frameworks

Introduction to Express

Express is a framework, but what's the difference between a framework and a library? The most important difference, and in fact the defining difference between a library and a framework is inversion of control. Basically, all the control flow is already in the framework, and there's just a bunch of predefined white spots that you can fill out with your own code. A library on the other hand is a collection of functionality that you can call.


Our First Express App

We started with a very simple Express app that will send some data back when we visit a certain route.

const express = require("express");
const app = express();
app.listen(3000, () => {
console.log(`Server running on port: 3000`);
});
app.get("/", (req, res) => {
res.send("Hi there!");
});
app.get("/bye", (req, res) => {
res.send(`Goodbye!`);
});
app.get("/dog", (req, res) => {
res.send(`Doggo`);
});

The package.json

package.json is a list of all the dependencies and metadata that our node_modules requires to run. We can set up our own package.json by using npm init.


How to Automate Server Restart

Use nodemon as a global dependency.


Route Params

If we want to have a catch-all route for when we type in a route that we don't have coded yet, we can use the * asterisk. What happens now is we will send an error saying "Error 404: Page not found" anytime someone tries to go to a page that we haven't coded yet.

app.get("*", (req, res) => {
res.send(`Error 404: Page not found`);
});

It's important to note that Express will match the first route handler it finds in chronological order in your code. So if we have our wildcard catch-all route * at the top of our code, it will catch any route requests even if they are valid routes that we have set up and it will send the error message. If we have any broadly catching routes we should put them at the bottom so that our specific routes can run if they are requested.

What if we have something like Reddit, where the url structure is as follows "reddit.com/r/soccer/comments/randomid/partoftitle". THere's no way we could hard code each of those routes into our Express configuration. This means that we need to use something called route parameters/route variables/path variables.

app.get("/r/:subreddit", (req, res) => {
res.send("Welcome to a subreddit");
});
// localhost:3000/r/puppies
// Welcome to a subreddit

If we want to take it one step further and make our routes dynamic so that when a user visits r/puppes we say Welcome to puppies we can do that by using the route parameters that Express gives us on req.params.

app.get("/r/:subreddit", (req, res) => {
res.send(`Welcome to r/${req.params.subreddit}`);
});
// localhost:3000/r/javascript
// Welcome to r/javascript

Express Basics Exercise

Our challenge was to create 3 Express routes. The first would be the root route and just say hello to the user. The second would be /speak/:animal and depending on the animal it would say /cow the cow says moo, or /pig the pig says oink. The third route was /repeat/:phrase/:num and it will take a phrase and repeat the phrase num amount of times.

const express = require("express");
const app = express();
app.listen(8080, () => {
console.log("Listening on something idk");
});
app.get("/", (req, res) => res.send("Hi there, welcome to my assignment!"));
app.get("/speak/:animal", (req, res) => {
const sounds = {
pig: "Oink",
cow: "Moo",
dog: "Woof",
};
const reqAnimal = req.params.animal;
res.send(`The ${reqAnimal} says ${sounds[reqAnimal]}`);
});
app.get("/repeat/:phrase/:num", (req, res) => {
const num = Number(req.params.num);
const phrase = req.params.phrase;
let message = "";
for (let i = 0; i < num; i++) {
message += ` ${phrase}`;
}
res.send(`${message}`);
});

Intermediate Express

Note about Templates and EJS

When using npm init to create a project, be sure to not name the project the same thing that a dependency is named otherwise there will be conflicts withing node_modules and other issues.


Templates and EJS

In this video we learned about how we can use EJS to dynamically render HTML templates in our views directory. We can run actual JavaScript code inside of our EJS which is then compiled to HTML.

const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.render("home.ejs");
});
app.get("/fallinlovewith/:thing", (req, res) => {
const thing = req.params.thing;
res.render("love.ejs", { thing });
});
app.listen(process.env.PORT, process.env.IP, () => {
console.log("Server is up!");
});

The EJS looks a little strange but here is the template for our love file.

<h1>You fell in love with: <%= thing %></h1>
<p>This is the `love.ejs` file</p>

We can also pass variables into our EJS by including an object with variables in our call to res.render.


EJS: Conditionals and Loops

We can use EJS to add logic to our ejs template files. This includes things like for loops to loop over data. We used the logic template feature to pass in an object of book titles and authors and inside of our ejs we used a for loop to loop over each object inside and make an li that contains the title and the author.

// Express
app.get("/posts", (req, res) => {
const posts = [
{ title: "Post 1", author: "John" },
{ title: "Post 2", author: "Nick" },
{ title: "Post 3", author: "Colt" },
];
res.render("posts.ejs", { posts });
});
// EJS
<h1>The Posts Page</h1>
<% for(let i = 0; i < posts.length; i++){ %>
<li><%= posts[i].title %> - <strong><%= posts[i].author %></strong></li>
<% } %>

There's a difference in the EJS syntax that's important to note.

  • <%= %> will automatically display whatever the result is of the code inside. EG.. 5+5 would render 10.
  • <% %> will not render what we put inside. This is where we would write our for loops.

Serving Custom Assets

  • Updated EJS Syntax -
<%- include("partials/header") %>
<%- include("partials/footer") %>

In this video, we learned about how to use partials to render pre-coded parts of HTML in our EJS files. It looks something like this...

<%- include("partials/header") %>
<h1>The Posts Page</h1>
<% for(let i = 0; i < posts.length; i++){ %>
<li><%= posts[i].title %> - <strong><%= posts[i].author %></strong></li>
<% } %>
<%- include("partials/footer") %>

Our header.ejs file lives in the views directory but in a special directory inside called partials, and we tell Express to look for our partials in that location.


Post Requests Part 1

We set up a simple express server and added a post route that will submit to our post route when we submit a new friend.


Post Requests Part 2

We set up a post request route and inside the route we're grabbing elements of the req body to add to our friends array. We also added body-parser so that we can grab things off the body of our requests. res.redirect was also used so that the user can stay on the friends page.


Working with APIs

Intro to APIs