For and While Loops

Page section: posts
More on loops

There are several kinds of traditional loops in JavaScript which are used considerably less since the introduction of various newer array iteration methods.

Nonetheless for, while and do .. while loops are still extremely useful.

for loops

for loops start like if statement with a regular bracket: for ( .... ) {

The basic syntax is:

for ( conditions to be met ) {
    ...run some code
}

Those conditions inside the brackets are to create a counter:

for (let i = 0; i < 21; i++) {
    // do this
}

The counter

The three conditions that need to be met are called the initializer, the condition and the final expression.

First a variable is defined for the counter and a starting point, let i = 0;.

Next the variable is given a maximum number. As always the count starts with zero so less than 3 is actually 3 counts (0, 1, 2): i < 3;

The third part adds to the variable each time: i++.

Here’s an example that goes through the array firstName.

for (let i = 0; i < 5; i++) {
    if (firstName[i] === "John") {
        alert("hello " + firstName[i]);
    }
}

NB i is usually used as a convention standing for iteration. However any variable name is fine.

To stop a loop from going on past where it needs to add the word break;

Sometimes you need to create flags which are variables, usually containing boolean values.

var x = false;

While loops

while loops in JavaScript are the simplest of all. They work like an if statement and the syntax is much the same. The loop runs while a condition, in parentheses, is true.

In the first example the loop executes the block of code as long as the variable i is less than 10. Each time through the loop the value of i is increased by 1: i++.

let i = 0;
while (i < 10) {
    console.log(`while loop no. ${i}`);
    i++;
}

In the above example the loop is broken when i exceeds 10. All loops must have a way to stop, that is the condition to be false. If they don’t then you get an infinite loop which carries on indefinitely and may crash the computer.

Do .. while loops

The do .. while loop is very similar to while loops. The difference is that the syntax is reversed. Here the code executes first before the condition to be met.

This means the loop will always run at least once even if the condition is never true.

do {
    alert(`do .. while loop no. ${i}`);
    i++;
} while (
    i < 4;
)

for … of loops

This is a simpler, newer way to create a loop for looping through arrays.

const myArray = ['dog', 'bear', 'civet', 'mongoose'];

for (let item of myArray) {
    console.log(item);
};

NB. The word item can be any valid string as long as it’s the same in both places.

Don’t confuse these with for ... in loops which are similar but for objects.

for (let item of shit) { 
    document.getElementById('shitlist').innerHTML += `${item} 1 <br>`
    }

NB. myArray is the name of the array to loop over. The word item could be anything. It does not matter other than it’s the same in both places.

High order array methods

Another way of looping through arrays is with array iteration methods like forEach().

  • forEach()
  • map()
  • filter()
  • reduce()

See High order array methods

  1. Tania Rascia has an excellent article on for loops. Also on while / do loops.
View contents of: /static/js/temp.js
// another temporary js file
View contents of: /static/js/tryout-arrays.js
const fruit = ["apples", "bananas", "cantaloupe", "dorians"];

const scientificFruit = [
  "Bell pepper",
  " Chile pepper",
  " Corn kernel",
  " Cucumber",
  " Eggplant",
  " Jalapeño",
  " Olive",
  " Pea",
  " Pumpkin",
  " Squash",
  " Tomato",
  " Zucchini",
];

const todos = [
  {
    id: 1,
    text: "Take out rubbish",
    isCompleted: true,
  },
  {
    id: 2,
    text: "Meet with boss",
    isCompleted: true,
  },
  {
    id: 3,
    text: "Dental appointment",
    isCompleted: false,
  },
];

function showFruit() {
  document.getElementById("fruitlist").innerHTML = fruit;
}

function fruitLoops(frt) {
  document.getElementById("fruit-loops").innerHTML += frt + '<br>';
}

const butt1 = document.getElementById("listfruit");

butt1.addEventListener("click", () => {
  document.getElementById("fruitlist").innerHTML = fruit;
});

const butt2 = document.getElementById("fruit2");

butt2.addEventListener("click", function () {
  document.getElementById("fruitlist").innerHTML = fruit[1];
});

const butt3 = document.getElementById("scientific");

butt3.addEventListener("click", function () {
  document.getElementById("fruitlist").innerHTML = scientificFruit;
});

const butt39 = document.getElementById("copying");

butt39.addEventListener("click", function () {
  const otherFruit = fruit.slice(1, 3);
  console.log("what apphen?");
  alert(`A new array called otherFruit now contains ${otherFruit}`);
});

// For buttons showing Array Methods

let myVar = [[1, "tree"], 2, 3, 4, 5, 6];
const mySubVar = ["frog", "Linsang", "stink badger"];

const showMyVar = document.getElementById("show-my-var");
const smvList = document.getElementById("smv-list");

function listMyVar() {
  smvList.innerHTML = ``;
  for (let i = 0; i < myVar.length; i++) {
    smvList.innerHTML += `<li>${myVar[i]}</li>`;
  }
}

showMyVar.addEventListener("click", () => {
  listMyVar();
});

const resetMyVar = document.getElementById("reset-my-var");

resetMyVar.addEventListener("click", () => {
  myVar = [[1, "tree"], 2, 3, 4, 5, 6];
  listMyVar();
  //   alert("reset");
});

Table of Contents