Loops in javaScript

Loops are a fundamental concept in computer programming. They allow us to repeat a set of one or more instructions a desired number of times.

Consider a simple javaScript program where we log "Solent University" to the console 5 times. You may take the following approach in solving this problem:

    console.log("Solent University"); 
    console.log("Solent University"); 
    console.log("Solent University"); 
    console.log("Solent University"); 
    console.log("Solent University");

The above approach works when we have to repeat an instruction a small number of times. However, as the number of times you have to repeat the same instruction or set of instructions increases, this approach becomes increasingly unfeasible. What if we now had to print run the instruction 1,000 times or even 1,000,000 times. In order to approach problems like these we need to utilise loops.

The two main types of loops that we'll user are:

  • for loops - used for a set number of iterations
  • while loop - used when a certain condition is true