Control Flow + More Data Types

Review: Terminology

In the following code, name the data types used, describe the scope for the variables, and spot the: statement, variable, expression, operator, function, argument, and return value.

function calculateTip(total) {
  const tipPercent = 0.15;
  return (total * tipPercent);
}

const billTotal = 10.00;
const billTip   = calculateTip(billTotal);
const receipt   = 'Total: ' + billTotal + ' Tip: ' + billTip;
console.log(receipt);

The if statement

Use if to tell JS which statements to execute, based on a condition.

if (condition) {
  // statements to execute
}
const x = 5;

if (x > 0) {
  console.log('x is a positive number!');
}

Comparison Operators

Use these operators to compare two values for equality, inequality, or difference.

  const myFavoriteNumber = 28;

Operator Meaning True expressions
== Equality myFavoriteNumber == 28
myFavoriteNumber == '28'
28 == '28'
=== Strict equality myFavoriteNumber === 28
!= Inequality myFavoriteNumber != 29
!== Strict inequality myFavoriteNumber !== '28'
28 !== '28'
> Greater than myFavoriteNumber > 25
'28' > 25
>=Greater than or equal myFavoriteNumber >= 28
'28' >= 25
< Less than myFavoriteNumber < 30
'28' < 30
<= Less than or equal myFavoriteNumber <= 28
'28' <= 28

Common mistake: Do not confuse = (the assignment operator) with ==.

Logical Operators

These are typically used in combination with the comparison operators:

const posNum = 4;
const negNum = -2;

Operator Meaning True expressions
&& AND posNum > 0 && negNum < 0

4 > 0 && -2 < 0
|| OR posNum > 0 || negNum > 0

4 > 0 || -2 > 0
! NOT !(posNum === negNum)

!(posNum < 0)

When combining together multiple conditions, use parentheses to group:

const myAge = 28;
if ((myAge >= 0 && myAge < 3)  || myAge > 90) {
  console.log('You\'re not quite in your peak.');
}

Truthy vs Falsey

If you don't use a comparison or logical operator, JS tries to figure out if the value is "truth-y".

const catsRule = true;
if (catsRule) {
  console.log('Yay cats!');
}

Values that are "false-y": false, the empty string (""), the number 0, undefined, null.

const name = '';
if (name) {
  console.log('Hello, ' + name);
}
const points = 0;
if (points) {
  console.log('You have ' + points + ' points');
}
let firstName;
if (firstName) {
  console.log('Your name is ' + firstName);
}

Short-Circuit Evaluation

JS evaluates logical operators from left to right and stops evaluating as soon as it knows the answer.

(false && anything) => false
(true || anything) => true

const numerator = 5;
const denominator = 0;
if (denominator !== 0 && (numerator / denominator > 0)) {
  console.log('Thats a valid, positive fraction');
}

The if/else statement

Use else to give JS an alternative statement to execute.

const age = 28;
if (age > 16) {
  console.log('Yay, you can drive!');
} else {
  console.log('Sorry, but you have ' + (16 - age) + ' years til you can drive.');
}

The if/else if/else statement

You can use else if if you have multiple exclusive conditions to check:

const age = 20;
if (age >= 35) {
  console.log('You can vote AND hold any place in government!');
} else if (age >= 25) {
  console.log('You can vote AND run for the Senate!');
} else if (age >= 18) {
  console.log('You can vote!');
} else {
  console.log('You have no voice in government!');
}

The while loop

The while loop tells JS to repeat statements as long as a condition is true:

while (expression) {
  // statements to repeat
}
let x = 0;
while (x < 5) {
  console.log(x);
  x = x + 1;
}

Beware: It's easy to accidentally cause an "infinite loop."

Also, otice how we're using let instead of const!

The for loop

The for loop is another way of repeating statements, more specialized than while:

for (initialize; condition; update) {
  // statements to repeat
}
for (let i = 0; i < 5; i = i + 1) {
  console.log(i);
}

We use i, j, k, etc. Harder to do an infinite loop, but still possible.

The break statement

To prematurely exit a loop, use the break statement:

for (let current = 100; current < 200; current++) {
  console.log('Testing ' + current);
  if (current % 7 == 0) {
    console.log('Found it! ' + current);
    break;
  }
}

The array data type

An array is a type of data-type that holds an ordered list of values, of any type:

const arrayName = [element0, element1, ...];

Yup, arrays use const - even though you can update the stuff inside them, it's still the same array!

const rainbowColors = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet'];
const raceWinners = [33, 72, 64];
const myFavoriteThings = ['Broccoli', 60481, 'Love Actually'];

The length property reports the size of the array:

console.log(rainbowColors.length);

Array access

You can access items with "bracket notation". The index starts at 0.

const arrayItem = arrayName[indexNum];
const rainbowColors = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet'];
const firstColor = rainbowColors[0];
const lastColor = rainbowColors[6];

Changing arrays

You can also use bracket notation to change the item in an array:

const myFavoriteThings = ['Broccoli', 60481, 'Love Actually'];
myFavoriteThings[0] = 'Celery Root';

Or to add to an array:

myFavoriteThings[4] = 'Playgrounds';

You can also use the push method:

myFavoriteThings.push('Dancing');

Using for loops with arrays and strings

Use a for loop to easily process each item in an array:

const rainbowColors = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet'];
for (let i = 0; i < rainbowColors.length; i++) {
  console.log(rainbowColors[i]);
}

or a string:

const rainbowColorsLetters = 'ROYGBIV';
for (let i = 0; i < rainbowColorsLetters.length; i++) {
  console.log(rainbowColorsLetters[i]);
}