Week 5 Promineo Tech

JS2-Conditions & Loops

Primitive Data Types

Primitive Data Types

  • Number
  • String
  • Boolean
  • Undefined
  • Null
  • Symbol
  • BigInt

typeof

prints out a value's data type

console.log(typeof 5); // number
console.log(typeof "") // string
console.log(typeof false) // boolean
console.log(typeof {}); // object
console.log(typeof function() {}); // function 
console.log(typeof undefined); // undefined
let myVariable;
console.log(typeof myVariable); // undefined

WARNING: Beware that typeof will return "object" for some things that we do not expect. For example, arrays and nulls will "object"

console.log(typeof null); // object WHAT?
console.log(typeof []); // object WHAT?

!

Integer

A number without a decimal point

Float

A number with a decimal point

Numbers

let year = 1990;
let timeGoneBy = 25;
year = year + timeGoneBy;
console.log(year); // 2015

Augmented

addition

let year = 1990;
let yearsAgo = 25;
year = year - yearsAgo;
console.log(year); // 1965

Augmented subtraction

let year = 1990;
let timeGoneBy = 25;
year += timeGoneBy;
console.log(year); // 2015
let year = 1990;
let yearsAgo = 25;
year -= yearsAgo;
console.log(year); // 1965

Augmented addition operator

Augmented subtraction operator

let year = 1990;
year = year + 1;
console.log(year); // 1991
let year = 1990;
year = year - 1;
console.log(year); // 1989
let year = 1990;
year ++;
console.log(year); // 1991
let year = 1990;
year --;
console.log(year); // 1989

Increment

operator

Decrement operator

Modulus Operator

const result = 20 % 8;
console.log(result); // 4

Returns the remainder in division

Order of Operations

  1. Parentheses
  2. Exponents
  3. Modulus
  4. Multiplication & Divison
  5. Addition & Subtraction 
const result = 5 * 2 ** (2 + 1);
console.log(result); // What is this?

Rounding with the Math Object

console.log( Math.round(0.5) );
// 1

Math.round()

rounds to the nearest integer

let wholeNum = Math.ceil(1.1);
console.log(wholeNum));
// 2

Math.ceil()

rounds up

const wholeNum = Math.floor(1.9);
console.log(wholeNum);
// 1

Math.floor()

rounds down

Strings

Strings

sequence of characters; text

"Bon appétit!"
'Bon appétit!'

Strings must be enclosed in either single or double quotes.

How to assign strings to variables and constants

let pokemonName = "Pikachu";
console.log(pokemonName); // Pikachu

const characterNames = 'Ash and Mindy';
console.log(characterNames); // Ash and Mindy

Get a Character by its Position

Use brackets [ ]

const letters = "abcdefghijklmnopqrstuvwxyz";
let letter = letters[12];
console.log(letter); // m

Note that the first character's position is 0.

String.length

counts the number of characters in a string

console.log("Pikachu".length); // 7

const pokemon = "Pikachu";
console.log(pokemon.length); // 7
const letters = "abcdefghijklmnopqrstuvwxyz";

How can I get z without knowing that the string below has 26 characters?

const letters = "abcdefghijklmnopqrstuvwxyz";
let letter = letters[ letters.length - 1 ];
console.log(letter); // z

String.indexOf()

gets the position number of a character

const letters = "abcdefghijklmnopqrstuvwxyz";
const index = letters.indexOf("m");
console.log(index); // 12

String.substring()

captures a piece of a string

const myString = "Soooooo";
const myStringShortened = myString.substring(0, 2);
console.log(myStringShortened); // So
"string".substring(startAt, endBefore);

NOTE that endBefore is optional. If you omit endBefore, your substring will end at the last character of the original string.

const fullName = "Coco Chanel";
// What can I do here so that it will print out "Chanel" below?
// This should get the last name for all full names
console.log(lastName);
const fullName = "Coco Chanel";
const index = fullName.indexOf(" ");
const lastName = fullName.substring(index + 1);
console.log(lastName); // Chanel

Remember, in most cases, a variable will not change without an = sign

let myVar = "Godfather, The";

// No equal sign ...
myVar.substring(0, 9);

// so myVar doesn't change
console.log(myVar); // Godfather, The

// But if we use an equal sign,
myVar = myVar.substring(0, 9);

// then myVar changes
console.log(myVar); // Godfather
let firstName = "Brian";
firstName[2] = "y";
console.log(firstName); // What is this?

This is an exception to the = sign rule

let firstName = "Brian";
firstName[2] = "y";
console.log(firstName); // Brian

String.replace()

replaces part of a string

let firstName = "Brian";
firstName = firstName.replace("i", "y");
console.log(firstName); // Bryan
"string".replace("whatToReplace", "replacement");
const firstName = "Richard";
const lastName = "Simmons";
console.log("firstName lastName"); // What is this?
const firstName = "Richard";
const lastName = "Simmons";
console.log(`${firstName} ${lastName}`); // Richard Simmons

You use ticks (`) instead of quotes.

You plugin values with ${value}.

Combines (concatenates) strings

Template Literals

let pokemon = "Pikachu";
pokemon + ", Charmander"
console.log(pokemon); // What would this be?
let pokemon = "Pikachu";
console.log(pokemon + ", Charmander"); // What would this be?
console.log(pokemon); // What would this be?

Remember, in most cases, a variable will not change without an = sign

const age = "55";
console.log(age + 10); // What is this?

JavaScript will convert numbers into a strings when you mix numbers and strings.

console.log("55" + "10"); // What is this?

Strings can contain number characters. When using the + symbol with strings, JavaScript will concatenate rather than add.

JavaScript is a

Loosely Typed Language,

meaning a variable's data type can change

Coercion

converting a value from one data type to another

parseInt()

converts (casts) strings into integers

const ageString = "55";
const ageNumber = parseInt(ageString);
console.log(ageNumber + 10); // 65

parseFloat()

converts (casts) strings as floats

const priceString = "10.95";
const priceNumber = parseFloat(priceString);
console.log(priceNumber + 1); // 11.95

More on strings

There are more methods that you can use. You can find them in MDN:

Booleans and

Control Flow

Booleans

true or false

let showMessage = true;
let showLoading = false;

If Statements

let isLoading = true;

if (isLoading) {
  console.log("Loading ..."); // Loading ...
}

console.log("The next thing");

Truthy

A value that is considered to be true when used in a boolean context

Falsy

A value that is considered to be false when used in a boolean context

  • true
  • "foo"
  • "0"
  • 42
  • -42
  • 3.14
  • -3.15
  • {}
  • []
  • new Date()
  • Infinity
  • -Infinity
  • false
  • ""
  • 0
  • undefined
  • null
  • NaN
  • document.all
if ("I am truthy") {
  console.log("Hello World");
  // Hello World
}

Will this print out "Hello World"?

if (0) {
  console.log("Hello World");
}

Is the page NOT loading?

Negation

A user clicks on a link to open a new page ...

Yes

Show page content

No

Move on to next thing

Negating Values

!value
let isLoading = false;

if (!isLoading) {
  console.log("Page content"); // Page content
}
let price = 0;

// Remember, 0 the number is falsy, and we are negating it
if (!price) {
  console.log("You must continue to checkout");
}

Is the page loading?

A user clicks on a link to open a new page ...

Yes

Show loading

Is there an error?

No

Yes

Show error

No

If ... Else If Statements

let isLoading = false;
let isError = true;

if (isLoading) {
  console.log("Loading ...");
} else if (isError) {
  console.log("Oops! There was an unexpected error");
  // Oops! There was an unexpected error
}
let hasSprinkles = true;
let hasChocoloateSyrup = true;

// What will we see here?
if (hasSprinkles) {
  console.log("Adding sprinkles to your Sundae");
} else if (hasChocoloateSyrup) {
  console.log("Adding chocolate syrup to your Sundae");
}

Only the code inside of the first true statement will execute.

let hasSprinkles = true;
let hasChocoloateSyrup = true;

// What will we see here?
if (hasSprinkles) {
  console.log("Adding sprinkles to your Sundae");
  // Adding sprinkles to your Sundae
} else if (hasChocoloateSyrup) {
  console.log("Adding chocolate syrup to your Sundae");
}
let hasSprinkles = true;
let hasChocoloateSyrup = true;

if (hasSprinkles) {
  console.log("Adding sprinkles to your Sundae");
  // Adding sprinkles to your Sundae
} 

if (hasChocoloateSyrup) {
  console.log("Adding chocolate syrup to your Sundae");
  // Adding chocoloate syrup to your Sundae
}

I can use multiple if statements to execute multiple true statements.

Is the page loading?

A user clicks on a link to open a new page ...

Yes

Show loading

Is there an error?

No

Yes

Show error

No

Show success

Else and Else If Statements

let isLoading = false;
let isError = true;

if (isLoading) {
  console.log("Loading ...");
} else if (isError) {
  console.log("Oops! There was an unexpected error");
  // Oops! There was an unexpected error
} else {
  console.log("Report generated successfully.");
}

String Comparison

a === b a strictly equals b
// Question: What is the W3C's name for JavaScript?
const studentAnswer = "ECMA";

if (studentAnswer === "ECMA") {
  console.log("Student gets a cookie!");
}
// Question: What is the W3C's name for JavaScript?
const studentAnswer = "ECMA";

const isStudentCorrect = studentAnswer === "ECMA";
console.log(isStudentCorrect); // true

Strict Not Comparison

a !== b a does not strictly equals b
// Question: What is the W3C's name for JavaScript?
const studentAnswer = "ECMA";

if (studentAnswer !== "ECMA") {
  console.log("Sorry, no treats for you. :(");
}

Number Comparison

a === b a strictly equals b
a !== b a does not strictly equal b
a > b a is greater than b
a < b a is less than b
a >= b a is greater than or equal to b
a <= b a is less than or equal to b
console.log(7 === 7); // true
console.log(7 !== 7); // false
console.log(7 > 10); // false
console.log(7 < 10); // true
console.log(7 >= 7); // true
console.log(7 <= 10); // true
const age = 15;

if (age >= 13) {
  console.log("You can see a PG13 movie");
  // You can see a PG13 movie
}

Boolean Comparison

Will this print out "Hello World"?

if (true === true) {
  console.log("Hello World!");
}

Will this print out "Hello World"?

if (false === false) {
  console.log("Hello World!");
}
if (true === true) {
  console.log("Hello World!"); // Hello World!
}
if (false === false) {
  console.log("Hello World!"); // Hello World!
}

Strict vs Loose Comparison

console.log("55" === 55); // false
console.log("55" !== 55); // true

Strict compares data type too

console.log("55" == 55); // true
console.log("55" != 55); // false

Loose guesses when the types are different

Will this print out "Hello World"?

if (0 == "") {
  console.log("Hello world");
}
if (0 == "") {
  console.log("Hello world"); // Hello World
}

Will this print out "Hello World"?

if (0 === "") {
  console.log("Hello world");
}

And Logical Operator (&&)

New hires, did you bring two forms of identification?

I have ...

Yes drivers license

Yes driver license

No driver license

No driver license

true

false

false

false

Driver License Passport
true && true true
true && false false
false && true false
false && false false

Yes passport

No passport

Yes passport

No passport

And Logical Operator (&&)

New hires, did you bring your required forms of identification?

const driverLicense = true;
const passport = true;

if (driverLicense && passport) { // true
  console.log("You can fill out your paper work.");
  // You can fill out your paper work.
}
const hasPermit = true;
const isAccompaniedByAdult = false;

if (hasPermit) {
  if (isAccompaniedByAdult) {
    console.log("You can drive");
  }
  else {
     console.log("You cant drive"); // You cant drive
  }
}
const hasPermit = true;
const isAccompaniedByAdult = false;

if (hasPermit && isAccompaniedByAdult) {
  console.log("You can drive");
} else {
  console.log("you cant drive"); // You cant drive
}

Or Logical Operator (||)

Are you participating in a track or field event?

I'm participating in...

Yes tack event

Yes track event

No track event

No track event

true

true

true

false

Track Event Field Event
true || true true
true || false true
false || true true
false || false false

Yes field event

No field event

Yes field event

No field event

const hasChicken = true;
const hasBeef = false;
const hasPork = false;
const hasFish = false;

if (hasChicken || hasBeef || hasPork || hasFish) {
  console.log("This meal is not vegetarian");
  // This meal is not vegetarian
}

You can use as many && or || as you need

Order of Operations

/**
 * You can drive a car under one of these two conditions:
 * 1.) You have a driver license
 * 2.) You have a driver permit and is accompanied by an adult
 */

const hasLicense = false;
const hasPermit = false;
const isAccompaniedByAdult = true;

if ((hasPermit && isAccompaniedByAdult) || hasLicense) {
  console.log("You can drive"); // Doesn't print "You can drive"
}

You can use () to change the order of evaluation. What is inside the () will be evaluated first.

Loops

Run a block of code on repeat

While Loop

Runs a block of code a specified number of times

let counter = 0;
while (counter < 10) {
  // This below says "Hello World" 10 times
  console.log("Hello World");
  counter++; // OR counter = counter + 1;

}

Step 1 Create a counter

Step 2 Create a condition of when to stop

What is inside of the { } repeats

Step 3 Update the counter

Your Turn

Create a while loop that uses a counter to stop

For Loop

Runs a block of code a specified number of times

for (let i = 0; i < 10; i++) {
  // This says "Hello World" 10 times
  console.log("Hello World");
}

Step 1

Step 2

Step 3

Step 1 Create a counter

Step 2 Create a condition of when to stop

What is inside of the { } repeats

Step 3 Update the counter

for (let i = 1; i <= 10; i++) {
  console.log(i * 10);
}
// 10
// 20
// 30
// ...
// 100
for (let i = 10; i > 0; i--) {
  console.log(i)
}
// 10
// 9
// 8
// ...

How would you count backwards from 10?

Your Turn!

  • Refactor your while loop into a for loopor loop.

Why we use let instead of var

var i = 2;

for (var i = 0; i < 5; i++) {
  // code
}

const myFunction = () => i;
console.log( myFunction() ); // What is this?
var i = 2;

for (var i = 0; i < 5; i++) {
  // code
}

const myFunction = () => i;
console.log( myFunction() ); // 5
let i = 2;

for (let i = 0; i < 5; i++) { // only code within the loop will refer to the i here
  console.log(i);
}

const myFunction = () => i;
console.log( myFunction() ); // 2

var can override and assign variables outside of a loop.

Ending a loop prematurely with

break

const abortAt = 3;

for (let i = 0; i < 100000000000; i++) {
  if (i >= abortAt) break;
  console.log(i);
}
// 0
// 1
// 2

deck

By Jamal Taylor