JS loops explained

by Dan Mathisen

HTML

<div id="result"></div>

JavaScript

// don't worry about this
var resultDiv = document.getElementById('result');

// this is what an array looks like
var array = [];
array[0] = "zero";
array[1] = "one";
array[2] = "two";
array[3] = "three";
array[4] = "four";

// OR more commonly it'll be writting like this:
// var array = ["zero", "one", "two", "three", "four"];

// these are two different ways of writing an array
// they will produce the exact same thing

// NOTE: arrays start at 0, not 1
// So the array "length" is 5 but the first item ("zero") is at "index" 0

// ANYWAY
// now we are going to loop through this array

// var i = 0 .... start at 0
// loop UNTIL i < array.length .... array.length = 5
// and AFTER EACH LOOP do i++ .... add 1 to i after each loop

for (var i = 0; i < array.length; i++) {
	// don't worry much about this stuff
  // just note that we're printing array[i]
	var message = "iteration " + i + ": " + array[i] + '<br/>';
  resultDiv.innerHTML += message;
  
  // The loop explained...
  
	// FIRST ITERATION
  // i = 0
  // array[0] = "zero"
  // so we show "zero"
  // then i++ means add 1 to i (now i is 1)
  // then loop again until i < array.length (i < 5)
  // 1 < 5 (this is true, so loop again)
  
  // SECOND ITERATION
  // i = 1
  // array[1] = "one"
  // so we show "one"
  // then i++ means add 1 to i (now i is 2)
  // then loop again until i < array.length (i < 5)
  // 2 < 5 (this is true, so loop again)
  
  // THIRD ITERATION
  // i = 2
  // array[2] = "two"
  // so we show "two"
  // then i++ means add 1 to i (now i is 3)
  // then loop again until i < array.length (i < 5)
  // 3 < 5 (this is true, so loop again)
  
  // FOURTH ITERATION
  // i = 3
  // array[3] = "three"
  // so we show "three"
  // then i++ means add 1 to i (now i is 4)
  // then loop again until i < array.length (i < 5)
  // 4 < 5 (this is true, so loop again)
  
  // FIFTH ITERATION
  // i = 4
  // array[4] = "four"
  // so we show "four"
  // then i++ means add 1 to i (now i is 5)
  // then loop...