name: inverse layout: true class: center, middle, inverse --- # JavaScript 101 Jared Egan - Resilient Coders --- layout: false # This class We will be working with just code & a console on JSBin.com. .medium[
Open JSBin here
. ] Ensure the "JavaScript" & "Console" tabs are displayed. After editing your JavaScript, you can re-run it with the keyboard shortcut "Ctrl" + "Enter". I recommend having this presentation & the JSBin website in 2 tabs. Retype the code to drill it into your brain. Copy & paste if you must and if you get behind. If you fall behind on the exercises,
find reference code (aka "the answers") here
. No looking ahead! You should try to solve the problems on your own first. --- # A Super Brief History of JavaScript .large[ - It's not Java - Used on the browser - Can run on back end servers, called Node.js - Very popular - Very strange. Has "good & bad parts" ] --- # Outline .large[ - Just code & console - Types & Values - Variables - Operators & Comparisons - Control Structures: if, while, for - Arrays - Functions & Methods - Objects ] --- # JSBin .large[ Using JSBin.
https://jsbin.com/?js,console
] --- # Dive In Your first "expression". ```javascript console.log('Hello, world!'); ``` --- # Dive In Your first "expression". ```javascript console.clear(); console.log('Hello, world!'); ``` --- # Variables Variables hold values, to be referenced later. ```javascript var foo = 'Hello, world!'; console.log(foo); foo = 'Goodbye, world!'; console.log(foo); ``` --- # Variables Variables hold values, to be referenced later. ```javascript var foo = 'Hello, world!'; var bar = foo; console.log(foo); console.log(bar); foo = 'Goodbye, world!'; console.log(foo); console.log(bar); ``` --- # Types & Values .medium[ - Number - String ✓ - Boolean - Object - Function - Array - Date - RegExp - null - undefined ] --- # Strings ```javascript // Single quotes or double quotes work var foo = "Hello, World!"; var bar = 'Hello, World!'; // Use the backslash for special characters console.log('JavaScript\'s fun.'); console.log('This is line one.\nThis is line two'); ``` --- # Comments Comments in code, for humans only. ```javascript // This is a comment to myself. var foo = "Hello, World!"; var bar = 'Hello, World!'; // It can be after a line of code. // Comment out code to stop it from running //console.log('JavaScript\'s fun.'); //console.log('This is line one.\nThis is line two'); /* Use this syntax... ...if you have a longwinded comment, or to comment out a lot of code. Just remember to close it! */ ``` --- # Numbers ```javascript var foo = 4; console.log(foo); var bar = 1.5; console.log(bar); ``` --- # Types & Values .medium[ - Number ✓ - String ✓ - Boolean - Object - Function - Array - Date - RegExp - null - undefined ] --- # Operators `+`, `-`, `*`, `/` and `%` ```javascript var foo = 4; console.log(foo); var bar = 1.5; console.log(bar); console.log(1 + 2); console.log(foo + bar); var result = foo * bar; console.log(result); ``` --- template: inverse # Exercise #1 Fahrenheit to Celsius --- # Exercise #1 Write a program that converts Fahrenheit temperatures into Celsius. Define a variable named `f`, and sets the value to `212`, to represent a Fahrenheit temperature. Store the calculated Celsius temperature into another variable named `c`. Print that variable with `console.log` To convert temperatures in degrees Fahrenheit to Celsius, subtract 32 and multiply by .5556. When `f` is set to `212`, the result should be `100.008` (Boiling) When `f` is set to `32`, the result should be `0` (Freezing) --- # Exercise #1 Gotcha: Order of operation If you got `194.2208`... .medium[ Math is evaluated in the following order: PEMDAS - Parentheses - Exponents - Multiplication - Division - Addition - Subtraction ] --- # '+' with strings Joins or "concatenates" two strings into one new string. AKA "concat". ```javascript console.log('Hello, ' + 'Dave'); // Works with variables var name = 'Jared'; var greeting = 'Hello, ' + name; console.log(greeting); // JavaScript will do its best with non-strings var numberOfCats = 4; console.log('There are ' + numberOfCats + ' cats.'); ``` --- template: inverse # Exercise #2 Variables, math & pizza. --- # Exercise #2 Write a program that defines 2 variables, `numOfPizzas` & `slicesPerPizza`. Set them to whatever numbers you'd like. Calculate the total number of slices and store that value into a new variable. (e.g. if there are 2 pizzas, with 6 slices per pizza, there are 12 slices total). Finally, print out the string: "There total number of slices is x" Or print everything: "There are x pizzas with y slices each, for a total of z slices." Remember: - JavaScript is case sensitive. `pizza` & `Pizza` are different. - Get one thing working at a time. --- # Additional operators .large[ `+=` and `-=` ] ```javascript var foo = 2; // These two lines do the same thing. foo = foo + 2; // 4 foo += 2; // 6 // Works with subtraction foo -= 2; // 4 ``` --- # Additional operators .large[ `++` and `--` ] Increments or decrements a variable by 1. ```javascript var foo = 2; foo++; console.log(foo); // 3 ``` --- # Comparisons - Equality .large[ - `a === b` Is `a` equal to `b`? - `a !== b` Is `a` not equal to `b`? ] Remember: `=` is for assignment. `===` is for comparison. --- # Boolean .large[ Either `true` or `false`. ] ```javascript var animal1 = 'cat'; var animal2 = 'dog'; var isCat = (animal1 === 'cat'); console.log(isCat); isCat = (animal2 === 'cat'); console.log(isCat); ``` --- # Types & Values .medium[ - Number ✓ - String ✓ - Boolean ✓ - Object - Function - Array - Date - RegExp - null - undefined ] --- # Comparisons - Less than/Greater than .large[ - `a < b` Is `a` less than `b`? - `a > b` Is `a` greater than `b`? - `>=` Greater than or equal to - `<=` Less than or equal to ] --- # Comparisons - Less than/Greater than ```javascript console.log(4 < 3); // false console.log(3 < 4); // true console.log(4 > 4); // false console.log(4 >= 4); // true ``` --- # Comparisons - A work of caution .large[ `==` vs. `===` - TL;DR: In JavaScript, Always use `===`. ] `==` does not check for type. So, `4 == '4'` returns `true`, even though `'4'` is a string, and `4` is a number. --- # Control Structures .large[ - `if` ] --- # `if` ```javascript var sound = 'meow'; if (sound === 'meow') { console.log('It\'s a cat!'); } ``` Exercise: Change the value of `sound`, does anything print? --- # `else` ```javascript var sound = 'meow'; if (sound === 'meow') { console.log('It\'s a cat!'); } else { console.log('Not a cat.'); } ``` --- # `else` ```javascript var sound = 'meow'; if (sound === 'meow') { console.log('It\'s a cat!'); } else { console.log('Not a cat.'); } if (sound === 'woof') { console.log('It\'s a dog!'); } else { console.log('Not a dog.'); } ``` --- # `else if` ```javascript var sound = 'meow'; if (sound === 'meow') { console.log('It\'s a cat!'); } else if (sound === 'woof') { console.log('It\'s a dog!'); } else { console.log('Unknown animal sound.'); } ``` --- # Logical OR & AND .large[ - `||` = OR - `&&` = AND ] --- # Logical OR `||` ```javascript var sound = 'meow'; if (sound === 'meow') { console.log('It\'s a cat!'); } else if (sound === 'woof') { console.log('It\'s a dog!'); } else if (sound === 'bark') { console.log('It\'s a dog!'); } else { console.log('Unknown animal sound.'); } ``` --- # Logical OR `||` ```javascript var sound = 'meow'; if (sound === 'meow') { console.log('It\'s a cat!'); } else if (sound === 'woof' || sound === 'bark') { console.log('It\'s a dog!'); } else { console.log('Unknown animal sound.'); } ``` --- # Logical AND `&&` ```javascript var hungry = true; var haveFood = false; if (hungry && haveFood) { console.log('Let\'s eat!'); } ``` --- # Logical AND `&&` ```javascript var hungry = true; var haveFood = false; if (hungry && haveFood) { console.log('Let\'s eat!'); } else if (hungry && !haveFood) { console.log('Let\'s go to a restaurant'); } else if (!hungry && haveFood) { console.log('Anyone want my food?'); } else { console.log('No food, no problem.'); } ``` Exercise: Copy & paste this into JSBin, and change the values to get all the different messages to print. --- template: inverse # Exercise #3 Age --- # Exercise #3 Write a program that prints out 'Baby', 'Child', 'Teenager' or 'Adult' depending on the value of a variable you define named `age`. Rules: - 0-4: Baby - 5-12: Child - 13-17: Teenager - 18 & up: Adult --- # "Truthy" & "Falsey" values .medium[ Expressions in conditionals don't have to be strictly `Booleans`. Falsey values: - `false` - `0` - Empty string (`''`) - `NaN` - "Not a number" - `null` - `undefined` Everything else evaluates to `true` ] --- # "Truthy" & "Falsey" values ```javascript var foo; // Default value for a var is `undefined` if (foo) { console.log('foo is true!'); } foo = 'something'; if (foo) { console.log('foo is true!'); } ``` --- # Control Structures .large[ - `if`, `else if`, `else` - loops: `while` & `for` ] --- # `while` loop A `while` loop evaluates a block of code over & over while the expression you give it is true. ```javascript var i = 0; while (i < 10) { console.log('i is: ' + i); i++; } ``` Exercise: Remove the line `i++;`. What do you think will happen? Run the code. --- # `while` loop ```javascript var i = 0; var stop = false; while (!stop) { console.log('i is: ' + i); i++; if (i === 10) { console.log('Stopping the loop.'); stop = true; } } ``` --- # `for` loop Similar to `while`, but allows you to specify control information in single line. More common. ```javascript for (var i = 0; i < 10; i++) { // Will execute 10 times } // Equivalent while loop: var i = 0; while (i < 10) { console.log('i is: ' + i); i++; } ``` --- template: inverse # Exercise #4 Basic loops --- # Exercise #4 Create a program that prints out "1 sheep", "2 sheep" all the way to "99 sheep". Solve this with a `while` loop, then solve it again with a `for` loop. --- # Types & Values .medium[ - Number ✓ - String ✓ - Boolean ✓ - Object - Function - Array - Date - RegExp - null - undefined ] --- # Array .large[ An object that holds a list of objects. ] --- # Array ```javascript var a = ['dog', 'cat', 'hen']; console.log(a.length); ``` --- # Array ```javascript var a = new Array(); a[0] = 'dog'; a[1] = 'cat'; a[2] = 'hen'; console.log(a.length); // 3 var a = ['dog', 'cat', 'hen']; console.log(a.length); // 3 ``` .medium[ `length` is a **property** the returns the total number of objects. It's always one more than the highest index. ] --- template: inverse # Exercise #5 Looping through an array --- # Exercise #5 Make array of strings of different animal names. Loop through the array and print out all the names. Bonus: Print out the word "meow" if the animal is a cat. --- # Exercise #5 Solution ```javascript var animals = ['dog', 'cat', 'hen', 'cat', 'cow']; for (var i = 0; i < animals.length; i++) { console.log(animals[i]); } ``` --- # Types & Values .medium[ - Number ✓ - String ✓ - Boolean ✓ - Object - Function - Array ✓ - Date - RegExp - null - undefined ] --- # Functions .medium[ Functions are blocks of code. - Can take input (aka "arguments") - Can return a value - They are "invoked", "called" or "applied" using `()` - Makes code reusable - Can be stored in a variable - Can have "side effects" ] --- # Functions Basic function ```javascript // Definition of the function function sayHello() { console.log('Hello'); } // Calling the function sayHello(); ``` --- # Functions Basic function ```javascript // Definition of the function function sayHello() { console.log('Hello'); } // Calling the function sayHello(); sayHello(); sayHello(); sayHello(); ``` --- # Functions Function that takes input and returns a value ```javascript // Definition of the function function sayHello(name) { return 'Hello, ' + name; } // Calling the function sayHello('Dave'); sayHello('Jared'); sayHello('Clarice'); ``` --- # Functions Function that takes input and returns a value ```javascript // Definition of the function function sayHello(name) { return 'Hello, ' + name; } // Calling the function var result = sayHello('Dave'); console.log(result); console.log(sayHello('Clarice')); ``` --- template: inverse # Exercise #6 Loop through array, call our function on each element. --- # Exercise #6 Create a `sayHello` function that takes a `name` argument and logs the phrase "Hello, {name}". Loop through our animals array and call that function with each element of the array. --- # Methods .large[ **Methods** are **functions** associated with an object. You call them on an object. ] --- # String methods ```javascript var str = 'I love JavaScript'; var yelling = str.toUpperCase(); console.log(str); // 'I love JavaScript' console.log(yelling); // 'I LOVE JAVASCRIPT' ``` --- # String methods ```javascript var str = 'I love JavaScript'; var char = str.charAt(0); console.log(char); // 'I' char = str.charAt(3); console.log(char); // 'o' ``` --- # String methods ```javascript var str = 'I love JavaScript'; var substr = str.substring(0, 6); console.log(substr); // 'I love' ``` --- # Array methods ```javascript var arr = ['one', 'two', 'three']; console.log(arr); arr.push('four'); // Adds a new item to arr console.log(arr); arr.pop(); // Removes the last item from arr console.log(arr); arr.reverse(); console.log(arr); console.log(arr.includes('two')); // true ``` --- template: inverse # Exercise #7 Find a method, call it. --- # Exercise #7 Look up a list of methods for string or array objects. Try one out, see what it does. Hot tip: Google for "javascript string methods" --- # Types & Values .medium[ - Number ✓ - String ✓ - Boolean ✓ - Object - Function ✓ - Array ✓ - Date - RegExp - null - undefined ] --- # Objects .medium[ "In classic Object Oriented Programming, objects are collections of data and methods that operate on that data." JavaScript objects can be thought of as simple collections of name-value pairs. Like a dictionary. Given a "key" or "name", you get a value back. ] --- # Objects: A basic object Created with curly braces `{}`. ```javascript var emptyObj = {}; var person = { firstName: 'Jimi', lastName: 'Hendrix', age: 27 }; // How to access values console.log(person.firstName); // preferred console.log(person['firstName']); ``` --- # Objects: A basic object ```javascript var person = { firstName: 'Jimi', lastName: 'Hendrix', age: 27 }; // How to access values console.log(person.firstName); // Set values person.firstName = 'Dave'; console.log(person.firstName); // Dave ``` --- # Objects: A basic object ```javascript var person = { firstName: 'Jimi', lastName: 'Hendrix', age: 27 }; // How to access values console.log(person.firstName); // Set values person.firstName = 'Dave'; console.log(person.firstName); // Dave // Keys are arbitrary, because JS is loose person.favColor = 'Orange'; console.log(person.favColor); // Orange console.log(person.firstName.toUpperCase()); // DAVE ``` --- # Objects ```javascript var person = { firstName: 'Jimi', lastName: 'Hendrix', age: 27, languages: ['JavaScript', 'HTML', 'Objective C'], address: { line1: '1 International Place', city: 'Boston', state: 'MA' } }; console.log(person.languages[1]); // HTML console.log(person.address.city); // Boston // Add 'Ruby' to languages array person.languages.push('Ruby'); console.log(person.languages); ``` --- template: inverse # Exercise #8 Print a pretty description of a person object --- # Exercise #8 Create a function named `describePerson` that takes an argument named `person` and logs out a description of the object. Given this object: ```javascript var person = { firstName: 'Jimi', lastName: 'Hendrix', age: 27, gender: 'male', languages: ['JavaScript', 'HTML', 'Objective C'], address: { line1: '1 International Place', city: 'Boston', state: 'MA' } }; ``` The output may be: "Jimi Hendrix is 27 years old." "He lives at 1 International Place, Boston MA" "He knows JavaScript, HTML and Objective C" --- # JavaScript Object Notation: JSON The data format is extremely popular. Used by most of the services you will consume. ```javascript var person = { firstName: 'Jimi', lastName: 'Hendrix', age: 27, gender: 'male', languages: ['JavaScript', 'HTML', 'Objective C'], address: { line1: '1 International Place', city: 'Boston', state: 'MA' } }; ``` --- # JSON Example Instagram API response for user profile ```javascript { "data": { "id": "1574083", "username": "snoopdogg", "full_name": "Snoop Dogg", "profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_1574083_75sq_1295469061.jpg", "bio": "This is my bio", "website": "http://snoopdogg.com", "counts": { "media": 1320, "follows": 420, "followed_by": 3410 } } ``` See more here: -
Instagram API Documentation
-
Twitter API Documentation
--- class:center # TO BE CONTINUED!