Loops and Iterators

Goals

  • differentiate between for loops, while loops and for in loops
  • be able to create a loop that terminates
  • be able to create an infinite loop
  • use a while loop correctly

what is a for loop?

What are the 3 sections?

for loop

var books = ["JavaScript: The Good Parts", "Eloquent JS", "You Don't Know JS"];

for (var i = 0; i < books.length; i++) {
    var book = books[i];
    console.log(book);
}
// JavaScript: The Good Parts
// Eloquent JS
// You Don't Know JS

while loop

while ( /* Boolean expression */ ) {
    Execute code
}

beware the infinite!

good while loop case

var total = 0;
var flip = Math.random();
while (flip > 0.5) {
  total++;
  flip = Math.random();
 }
console.log("Number of consecutive times heads came up: " + total);
  • Good to use while loop when loop will repeat an unknown number of times
  • BUT the loop will end at some point!

for-in loop

var person = {
  firstName: "Homer",
  middleName: "Jay",
  lastName: "Simpson",
};

for (var key in person) {
  console.log(key);
}
var person = {
  firstName: "Homer",
  middleName: "Jay",
  lastName: "Simpson",
};

for (var key in person) {
  console.log(person[key]);
}

for-in loop

var person = {
  firstName: "Homer",
  middleName: "Jay",
  lastName: "Simpson",
};

for (var key in person) {
  console.log(key);
}
var person = {
  firstName: "Homer",
  middleName: "Jay",
  lastName: "Simpson",
};

for (var key in person) {
  console.log(person[key]);
}

Your turn!

using a while loop,

log out 99 bottles of beer

Your turn!

using a for-in loop,

log out all the values in numbersObj squared

var numbersObj = {
  numberOne: 2,
  numberTwo: 4,
  numberThree: 20,
  numberFour: -7
}

Goals

  • differentiate between for loops, while loops and for in loops
  • be able to create a loop that terminates
  • be able to create an infinite loop
  • use a while loop correctly

loops and iterators

By Matthew Williams

loops and iterators

  • 776