GDI Logo

Intermediate JavaScript

Class 1

Get the course!

Download the course files - https://github.com/gdi-nyc/gdi-intermediate-javascript

download course instruction

Can view slides at - https://gdi-nyc.github.io/gdi-intermediate-javascript/

Agenda

  • Intro
  • JavaScript Programming Refresher
  • Some JS conveniences

Welcome!

Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.

  • Instructor & TA Intro
  • Classroom == Safe Space
  • Help each other
  • Have fun!

Some "rules"

  • GDI Code of Conduct
  • Every question is important
  • Failure = learning
  • Your keyboard is lava (for instructors)

Quick Logistics!

  • Where's the bathroom?
  • Who's camera shy?
  • Get on Slack!

Breaking the ice!

  • What's your name?
  • What do you hope to get out of this class?

This is what we'll be making!

JavaScript Refresher!

What is JavaScript?

An object-oriented computer programming language commonly used to create interactive effects within web browsers.

JS History

  • Created by Brendan Eich in 1995

  • Inspired by Java
  • Standardized - European Computer Manufacturers Association Script (ECMAScript)
  • ECMAScript 1 (1997)
  • ECMAScript 2 (1998)
  • ECMAScript 3 (1999)
  • ECMAScript 5 (2009)
  • ECMAScript 2015 (AKA ES6)

Variables

Variables store information


let age = 26; // Can change this variable
const name = "Marry"; // Cannot change this variable

Note: best practice is to prefer using "const"

Data Types

Three most common types of data


56; // Number

"blah blah"; // String

true; // Boolean
          

POP QUIZ!

Name that data type!

17

false

"false"

1

"525600"

true

POP QUIZ - Answers!

Name that data type!

17 - Number

false - Boolean

"false" - String

1 - Number

"525600" - String

true - Boolean

Math Operators


5 + 6; // 11
9 - 4; // 5
3 * 5; // 15
4 / 2; // 2
2 ** 3; // 8
16 % 5; // 1

The last one, %, is called modulo - it returns the remainder of the division

Modulo is often used to check for even division


// Checking for evenness
let amount = 2206;
amount % 2; // 0
amount % 2 === 0; // true

361 % 8; // 1
361 % 8 === 0; // false

Arrays

  • Arrays store multiple pieces of information, or items
  • Each item is referenced by it's index, or spot in "line"
  • Order matters!
  • Indexing starts at 0!

const students = ["Cheryl", "Sammy","Marty"];
students[0]; // "Cheryl"
students[1]; // "Sammy"

students[0] = "Billy"; // reassignment
console.log(students); // ["Billy", "Sammy","Marty"]

students[5]; // undefined

POP QUIZ!


const colors = ["blue","red","green","cyan","yellow","orange","#000000"];

How would you access "cyan"?


colors[3];
  

What string is at the 5th index?


colors[5]; // "orange"
  

How would you access the last item in the array?


colors[6]; // technically correct...
colors[colors.length-1]; //👍 programmers #1 choice

How would you reassign the last item to "black"?


colors[colors.length-1] = "black";
  

Loops

Loops allows the same block of code to be executed multiple times in succession

The 2 most common loops are the "for" and "while" loop

"for" loop

for loop breakdown

"for" loops + arrays = 🎉


const students = ["Marry","Barb","Phil"];
// Loops through array and console.logs each item
for(let i = 0; i < students.length; i++){
  const student = students[i]; // iterator, i, used as index
  console.log(student);
}

"while" loop

Works much like the "for" loop, but the 3 parts (initialization, condition, and final expression) are delegated differently


const students = ["Marry","Barb","Phil"];
// Loops through array and console.logs each item
for(let i = 0; i < students.length; i++){
  const student = students[i]; // iterator, i, used as index
  console.log(student);
}

const students = ["Marry","Barb","Phil"];
let i = 0; // initialization OUTSIDE of "while" loop
while(i < students.length){ // condition - eventually must evalauate to false!
  const student = students[i];
  console.log(student);
  i++; // final expression
}
    

Conditionals

  • Conditional statements allow for code to be differentially executed based on specific conditions
  • "if" and "if/else" statements are the most common conditional statements

const age = 23;
if(age > 18){
  console.log("Welcome to the casino!");
}else{
  console.log("YOU SHALL NOT PASS!");
}

Logical Operators

Just like math operators, logical operators allow us to govern how logical expressions are evaluated and will always evaluate to a boolean


5 > 4; // true
12 < 6; // false
16 >= 4; // true
3 <= 7; // true
"this" == "that"; // false (checks equality)
"GDI" != "GDI"; // false (checks inequality)

Boolean Operators

Boolean operators allow us to combine logical expressions in more complex ways


// ||
// OR - returns true if one side evaluates to true
true  || true;  // true
true  || false; // true
false || true;  // true
false || false; // false
// &&
// AND - returns true if BOTH sides evaluate to true
true  && true;  // true
true  && false; // false
false && true;  // false
false && false; // false
// !
// NOT - negates the logical expressions that follows
!true;  // false
!false; // true
          

Truthy vs. Falsey

  • Values that can be coerced into true are "truthy"
  • Values that can be coerced into false are "falsey"


There are fewer "falsey" values, so let's define them and consider everything else as "truthy"


if (false) // actual false
if (null)

if (undefined) // such as a variable defined unassigned variable
let x; // undefined by default
if (x)

if (0) // zero!
if (NaN) // Not A Number, can happen if you add undefined to a number
if ("") // empty string
            

BREAK

Functions

Functions are a way to store code to be executed later


function coinFlip(){
  // Math.random() returns a random decimal between 0 and 1
  return Math.random() > .5;
}

Defining Functions

MANY ways to define a function in JS. Here are a few basic ways.


function coinFlip(){
  return Math.random() > .5;
}

const coinFlip = function(){
  return Math.random() > .5;
}

const coinFlip = () => Math.random() > .5; // We'll dive into this later!

Functions with parameters

Functions can accept arguments, or information passed into them when they are called


function getTotalPrice(price, tax){
  return price * (1 + tax);
}

getTotalPrice(100, .08); // 108

Let's Develop It!

In the "mainProject" folder, go into "class_1", and edit the "script.js" file

  • Let's psuedocode this together!
  • Create a function "randomItem" that takes 1 argument: an array
  • The function should return a random item from the given array

HINT:


// Math.random() returns a random decimal in the range of 0 and 1
Math.random(); // 0.231657 a random number in the range of 0 and 1

// You can scale up a range through multiplication
const val = Math.random() * 12; // 5.632467 a random number in the range of 0 and 12

// Math.floor() removes the decimal part of a number
Math.floor(val); // 5

One possible solution...


const randomItem = function(arr){
  const randDecimal = Math.random();           // decimal b/t 0 and 1
  const randNumber = randDecimal * arr.length; // number b/t 0 and arr.lenth
  const randIndex = Math.floor(randNumber);    // whole number b/t 0 and arr.length
  return arr[randIndex];
}
            

Ternary Operator

The ternary operator is another way of representing an "if/else" statement in one line


const user_authenticated = false;
let message;
if(user_authenticated){
  message = "Welcome to your homepage!";
}else{
  message = "Access Denied!";
}
console.log(message); // "Access Denied!";
            

const user_authenticated = false;
let message = user_authenticated ? "Welcome to your homepage!" : "Access Denied!";
console.log(message); // "Access Denied!";
            

NOTE: it's best practice to only use the ternary operator when the logic and values are simple

Arrow Function

Similar to the ternary operator, the arrow function helps keep simple functions succinct and on 1 line


const seasonOfLove = function(){
  return 525600;
}

const seasonOfLove = () => 525600;
// No parameters, therefore use empty parentheses
// One line, no need for brackets
// and automatically returns everything after the arrow
                        

const minutesFromYears = num_of_years => num_of_years * 525600;
// With 1 parameter, can just use parameter without parentheses

const add = (num1,num2) => num1 + num2;
// With more parameters, need parentheses
                        

const minutesFromYears = num_of_years => {
  const leapDays = Math.floor(num_of_years / 4);
  return (num_of_years * 525600) + leapDays;
};
// With larger blocks of code, can use multiple lines,
// brackets, and an explicit return statement

Let's Develop It!

In the "mainProject" folder, go into "class_1", and edit the "script.js" file

  • Let's psuedcode the "randomizeArray" function together!
  • Work in pairs to create the function

HINT:


const students = ["Billie","Jean","Izzinot Mye"];
// .push() adds an item to the end of the array.
students.push("Love R.");
console.log(students); // ["Billie", "Jean", "Izzinot Mye", "Love R."]

// .splice() takes 2 arguments: an index and a count.
// Items are removed from the array starting at the given index
// Removal stops after the count is reached. 
// The removed items are returned in an array.
const removed = students.splice(2,1); // Starting at index 2, remove 1 item
console.log(removed); // ["Izzinot Mye"] <- It's an array!
console.log(students); // ["Billie", "Jean", "Love R."]

Take Home Assignment

  • Finish the tasks in the "script.js" file
  • Test to make sure the "randomizeArray" function works properly - we'll be using this function for the rest of the course!
  • Tackle as many bonuses as you can!

Additional Resources

"while" loop trickery

Since each part of the loop is separate, we can often get away with more succinct code


const students = ["Marry","Barb","Phil"];
while(students.length){ // 0 equals false
  const student = students.shift(); // removes first item from array
  console.log(student);
}

const students = ["Marry","Barb","Phil"];
while(students.length) console.log(students.shift()); 
// No need for brackets when all on one line
  

WARNING: Beware the infinite "while" loop where the condition is always true!