JavaScript 101

Part 2
Control Flow and More Data Types

Review: Terminology

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

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

Review: Terminology

statement
console.log(receipt);
variable
var billTotal = 10.00;
expression
var receipt = 'Total: ' + billTotal + ' Tip: ' + bill;
operator
+

Review: Terminology

function
function calculateTip(total) {
  var tipPercent = 0.15;
  return (total * tipPercent);
}
          
argument
(total)
(billTotal)
return value
return (total * tipPercent);

Control Flow

if statements

The if Statement

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

What if looks like:

if (condition) {
  // statements to execute
}

How if Works

if statements execute only if your condition is true. Example:

var x = 5;

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

What happens here?

Operators

Comparison Operators

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

Comparison Operators

  • Compares the expressions (operands) to the left and right of the operator and returns true or false
  • Operands can be any expression that resolves to a value
  • If the operands aren't the same type, JavaScript tries to convert before comparing, except for...
  • Strict comparisons don't attempt conversion

Equality

var myAge = 26;
if (myAge == 26) {
    // stuff
 }

Important!
Don't confuse assignment (=) with equality comparisons (==)!

Strict equality

var myAge = 26;
if (myAge === 26) {
    // stuff
}

What happens when we do this?

var age = '26';
if (age === 26) {
    // stuff
}

Inequality

var myAge = 26;
if (myAge != 26) {
    // stuff
}

Strict inequality

var myAge = 26;
if (myAge !== 26) {
    // stuff
}

Greater than

myAge > 26

Less than

myAge < 26;

Greater than or equal

myAge >= 26

Less than or equal

myAge <= 26 

Logical Operators

AND, OR, NOT

Logical Operators

  • Typically used with comparison operators
  • Compare two operands and returns true or false
  • Allow you to test several conditions at once
  • Always read left to right
  • Only continues testing if needed

AND - &&

Returns true if: both statements are true.

var posNum = 4;
var negNum = -2;

True expressions:

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

False expressions:

posNum > 0 && negNum > 0
4 > 0 && -2 > 0

Inclusive OR - ||

Returns true if: either statement (or both) is true.

var posNum = 4;
var negNum = -2;

True expressions:

posNum > 0 || negNum > 0
4 > 0 || -2 > 0

False expressions:

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

Negation - !

Inverts the truth of another expression

var wants_to_dance = true;
var friends_of_mine = true;
if (!wants_to_dance) {
    friends_of_mine = false;
}

Increment/Decrement ++ / --

Used to increment or decrement a variable by one

var start = 0;
start++;
console.log(start); // 1
console.log(start++); // Postfix - 1
console.log(start); // 2
console.log(++start); // Prefix - 3

Most commonly used in a for loop

Using mutiple operators

When combining together multiple conditions, use parantheses to group:

var friends = false;
if (favorite_band === 'The Mountain Goats' || has_beer) {
    friends = true;
}

Operators

An important lesson: truthy and falsey

Truthy

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

var dogsRule = true;
if (dogsRule) {
  console.log("Yay dogs!");
}

Falsey

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

var name = '';
if (name) {
  console.log("Hello, " + name);
}

var points = 0;
if (points) {
  console.log("You have " + points + " points.");
}

var firstName;
if (firstName) {
  console.log("Your name is " + firstName);
}

Short-Circuit Evaluation

How JavaScript saves us time!

Short-Circuit Evaluation

JavaScript evaluates all logical operators from left to right. It stops evaluating as soon as it knows the answer.

When it stops depends on the operator you're using.

Short-Circuit Evaluation: &&

Stops as soon as it hits a false expression because it requires all things to be true.

var name = "";
var age = 26;
if (name && age) {
  console.log("Hello!);
}

Because name is false, it won't ever get to age.

Short-circuit evaluation: ||

Stops as soon as it hits a true expression because it only needs one thing to be true.

var name = "";
var age = 26;
if (name || age) {
  console.log("Hello!);
}

name is false, but age is true, so this goes the whole way through.

If we change this around to:

if (age || name) {
  console.log("Hello!);
}

age is true, so it stops evaluating.

Control Flow

if, else if, and else statements

if/else statements

Use else to give JavaScript an alternative statement. else runs when the if statement fails.

...
if (is_admin) {
    delete_user();
} else {
    alert('Only admins can delete users');
}

if/else/else if

If you want multiple checks, you can use else if to run through them all.

...
if (!zipcode) {
    console.log('No name given');
} else if (zipcode.length !== 5 || isNaN(parseInt(zipcode, 10))) {
  console.log("Invalid zipcode");
} else {
    console.log("Your zipcode is " + zipcode);
}

Exercise!

if/else

If you get stuck, raise your hand.

Loops

  • while
  • do/while
  • for

while loop

The while loop tells JavaScript to repeat statements while the condition remains true

var x = 0;
while (x < 5) {
  console.log(x);
  x++;
}

do/while

Exactly like while but will run the body at least once before quitting

var name = null;
do {
  name = prompt('What is your name?');
} while (!name);
console.log(name);

Pretty rare with specific use-cases

for loop

The for loop is another way of repeating statements, more specialized than while. There are more pieces:

for (initialize variable(s); condition; update) {
// statements to repeat
}

for loop

What it looks like with real values:

for (var i = 0; i < 5; i++) {
  console.log(i);
}

The for loop used when you have a known start/stop for your loop

break

To prematurely exit a loop, you can use the break statement:

for (var current = 100; current < 200; current++) {
  console.log("Testing " + current);
  if (current === 155) {
    console.log("Found it! " + current);
    break;
  }
}

continue

Used to skip an iteration

for (var current = 100; current < 200; current++) {
  if (current === 155) {
      console.log('Skip 155');
      continue;
  }
  console.log('Current: ' + current);
}

Exercise!

Loops

If you get stuck, raise your hand.

Arrays

A data type containing an ordered list of values.

Arrays

Arrays are a data type that hold an ordered list of values. These values can be any type. Arrays look like this:

var arrayName = [element0, element1, element2];

We can make an array of our favorite bands:

var favoriteBands = [
  "The Mountain Goats", "Timber Timbre", "Fleet Foxes"
]

And find out the length (property):

console.log(favoriteBands.length);

Accessing things in arrays

You can access things in an array using bracket notation and the index (location). The first item in your array is at index 0 (Blame Martin Richards)

var colors = ['Red', 'Orange', 'Yellow', 'Green'];
var firstColor = colors[0];
var lastColor = colors[colors.length - 1];

Changing items in arrays

You can also use bracket notation to change items in the array.

var favoriteBands = [
  "The Mountain Goats", "Timber Timbre", "Fleet Foxes"
];
favoriteBands[1] = 'Valaska';

Adding items to arrays

Adding to an array is done with the push() method of the array

var favoriteBands = [
  "The Mountain Goats", "Timber Timbre", "Fleet Foxes"
];
favoriteBands.push("Good Old War");
console.log(favoriteBands);

Iterating through arrays - for

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

var rainbowColors = [
  "red", "orange", "yellow", "green", "blue", "indigo", "violet"
];

for (var i = 0; i < rainbowColors.length; i++) {
  console.log(rainbowColors[i]);
}

Iterating through arrays - forEach

Modern browsers (IE9+) support the forEach method, which is cleaner than a for loop

var rainbowColors = [
  "red", "orange", "yellow", "green", "blue", "indigo", "violet"
];

rainbowColors.forEach(function (color, index) {
  console.log(color);
});
// compared to
for (var i = 0; i < rainbowColors.length; i++) {
  console.log(rainbowColors[i]);
}

Exercise!

Arrays

Getting help

Google for questions or check Stack Overflow. Also look on the Mozilla Developer Network.

Homework

Number guesser