JavaScript Loops

JavaScript Loops

·

10 min read

Computers are super efficient at running a large number of simple tasks! As programmers, we take advantage of this speed by writing programs that will repeatedly do some task until a specific condition is met.

If I wanted to scan hundreds of books for a word, it would take me a long time! We can write programs to do these kinds of tasks in seconds.

Let's think about how we would tell a computer to read a bunch of books.

First, we can tell the computer to read each book until there are no books left. Then we can tell it to read each page in the book until there are no pages left. Then each word on the page until there are no words left. Each of these can be written in what we call loops.

while we have books

read book

while we have pages in this book

read page

while we have words on the page

read the word

In a flow chart, this may look like this:

Observe the flow chart and you can see how we read each word until we have no words, read each word until we have no more pages, and read each book until we have no new books.

Excited to build some loops? Let's get coding!

Loops

Oftentimes we need to write code to repeatedly do some task until a certain condition is met. This is where we can use loops! For instance, let's consider how to sum the numbers 1,2,3 and 4 in a loop:

First, we start with 1 and add this to the sum. Then we move to 2, add this to the sum... and so on until we reach 4. Each time we add to the sum is an iteration. We iterate until we reach our exit condition when the value is greater than 4.

For a more real-world example

We want to write a program, to sum up all the numbers in an excel sheet. What are the steps?

  1. Create a sum variable to hold our total value

  2. Create a row variable to remember where we are in the sheet

  3. Move to the current row. Add the value to our sum.

  4. Are we out of rows? If yes, return the sum. If no, add 1 to our row counter. Then go back to step 3.

You can see there are four iterations in our illustration above. Each iteration adds the value in the row to the sum and then increments the row so we move on to the next row.

Often in programming rows will be 0 indexed, meaning the first row will start at 0. We'll talk more about this when we dive into arrays!

For Loop

Let's take a look at a JavaScript for loop:

let sum = 0;
for(let i=1; i<=4; i++){
    sum +=i;
}

This loop sums every number up t 4 using an index i which starts at 1 and is incremented each iteration.

  1. The i variable will start at 1 (let i=1).

  2. It will be added to the sum ( sum +=i).

  3. Then we will check the condition to see if we should continue the loop (i <=4). Since i, at this point, in 1 and indeed less than or equal to 4, we'll continue.

  4. We add one to i (i++) and the loop starts again with i now being 2.

  5. Run steps 2-4 until the condition breaks us out of the for loop.

The loop continues until the condition (i<=4) is false. In this sample, when i got to 5, it did not meet the condition set so the loop ended and is no longer executed. The result of the above is we added 1, 2, 3, and 4 to our sum, resulting in a total sum of 10.

Let's break this loop down into components

Components

Let's take the for loop and break it down:

let sum = 0;
for(let i = 1; i<=4; i++){
    sum = sum + i;
}

The for loop can be broken down into the initialization, condition, update and statement:

for([initialization]; [condition]; [updata]){
    statement
}
let i = 1;

The Initialization is run once at the beginning of the loop. Create a variable in this expression and initialize the starting value.

i <=4;

The condition is checked before each iteration. If the expression evaluates to true, the statement will run. If it is false the statement will not run.

i++;

The Update is run at the end of each iteration. It can update a variable for the execution of the statement. Typically this will increment or decrement some running counters like i in this case.

You might be wondering about the ++ operator here! It's a new one we haven't seen yet. It's commonly referred to as the increment operator and means to add one to the variable. i++ is the same as i = i+1.

{sum = sum + i;}

Finally, the Statement is run as long as the Condition is true. This is where the real work of the loop gets done. If you're counting the sum of a bunch of numbers you might add I to the sum total in each iteration.

Another operation you can use is += The statement sum +=i would be a shortcut for sum = sum + 1 The operator takes the right-hand side and adds it to the left-hand side, assigning the new value to the left-hand side variable.

Factorial

In mathematics, a factorial is often denoted with an exclamation mark! A factorial is the product of all positive integers greater than 0 up to and including the factorial number n.

Let's take a look at a few examples of factorials:

5! = 5*4*3*2*1 = 120

3! = 3*2*1 = 6

2! = 2*1 = 2

As you can see above, 5! pronounced "five factorials", is 5*4*3*2*1. The number n, in this case, 5, is multiplied by every whole number below it greater than 0, resulting in a product of 120.

Let's think about how this translates to a loop

Factorial to Loop

Le's say we wanted to find the factorial of five: 5!

We know this to be 5*4*3*2*1. So how do we program our loop to multiply this out?

First, we'll want to initialize the resulting value:

let result = 1;

Next, we'll want to work on our for a loop. Remember that we can break it down into for components:

for([initialization]; [condition]; [update] ){
    statement
}

We'll need to initialize our index I to start at 1:

let i = 1;

Then we'll want to set the condition that we want to reach the number 5:

i <= 5;

Then we'll want to set the update to increment our index i:

i++;

Finally, our statement will be to multiply the result by the new index i:

{result = result * i;}

Just like in the last stage, there is a shortcut operator you can use here: \=. The expression would look like result *= i

Finally, we need to take what we've done here and generalize it. Instead of using 5, in the code exercise, we'll want to multiply each number from 1 until n and accumulate the result.

We could also count down from, although that's a bit trickier. Can you think how that would work?

String Loops

So far we have used loops to add and multiply to some total integer value. Nevertheless, there are many other uses for loops! Let's think about how we can use them from strings.

Let's add some exclamation marks to "Hello World"

let str = "Hello World";
for(let i = 1; i<=5; i++){
    str+="!";
}
console.log(str);
//Hello World!!!!!

Use the + operator to add two or more strings together!

In this case, above, we are adding an exclamation mark to our str every iteration. We iterate 5 times so we end up with 5 exclamation marks at the end of "Hello World".

Let's examine the parts of our for loop

Remember the for parts in our for loop:

for([initialization]; [condition]; [updata]){
    statement
}

We'll begin with an empty string:

let str = "";

During our initialization, we'll define our index variable:

let i = 1;

And we'll keep counting until we reach our value n:

i <= n;

Once again, we will update by incrementing our index i:

i++;

Finally, our statement is, This is the only major difference from the last two stages. We'll want to add to our string:

{ str += "a" }

As mentioned in the previous two stages, += is shorthand for str = str + "a". This will append our two strings together with "a" being added to the end of str

Modulus Operator

Time to learn a new operator: % This operator is called to modulus operator. It will tell us the remainder of a division.

When you divide 8 by 3 you get 2 and two-thirds. Or 2 with a remainder of 2.

The expression 8%3 evaluates to that remainder: 2

Let's take a look at a few examples:

console.log(8%3);//2
console.log(5%2);//1
console.log(7%4);//3

Let's examine how we can use modulus in loops!

Modulus in Loops

How many even numbers are there from 1 to 11?

How might we program a computer to figure this out?

First, we need to figure out how to recognize an even number! Let's say we have some number num:

const remainder = num %2;
const isEven = remainder ===0;

Here we have boolean isEven that will tell us whether or not the remainder is 0. When the remainder is 0, the num is evenly divisible by 2. When a number is evenly divisible by 2, it is even by definition!

To get a count from 1 to 11 of the total even numbers we could simply use a for loop like we have been doing:

let count = 0;
for(let i=1; i<=11; i++){
    const remainder = i%2;
    const isEven = remainder === 0;
    if(isEven){
        count++;
    }
}
console.log(count);

We get a count of 5 because there are 5 even numbers between 1 and 11. The number are 2, 4, 6, 8, and 10!

Top Double

OK, this one will be a bit of a difficult challenge!

The objective is to double a value until just before it reaches the top.

Let's say our value is 2 and our top is 100. We would double it like so:

2, 4, 8, 16, 32, 64, 128

We start at 2, double to 4, 8, and so on until 128. We recognize 128 is larger than our top 100 so we return 64. This is the to double for 2 before 100.

The desired result for topDouble(2, 100) would be 64.

Another loop that will be useful for this task is the will loop

While Loop

A new useful type of loop for this challenge is the while loop:

while(b>5){
    //do something
}

Below you can see we are simply providing a condition true that this statement will execute until that condition is false.

Also helpful is the break statement:

while(true){
    if(a>2){
        //exit the loop
        break;
    }
}

Once the break is hit, we will exit the loop. Even though the condition is true the break statement still gives us a way to exit the loop.

You can also exit a loop by using return, which will exit the function and return the value you designate.

Hope you are enjoying my blog so far next we'll discuss String Manipulation in the following blog till then keep coding.