Mastering JavaScript Loops

Kinanee Samson - Dec 26 '20 - - Dev Community

Good day guys, This article is going to be focusing on loops and how they are implemented in JavaScript. We will be covering loops first, to understand the concept of loops and then we will dive into how we can iterate a process in JavaScript, I mean how repeat a process.

Loops

First thing first we need to examine the idea of loops. There are times when you're coding and you have to repeat a particular set of instructions or call a function on a list of items
We might not know the total amount of item in the list or the exact number of times we want to repeat the block of code, and even when we know how much we want to repeat the task, manually specifying is not a great way to write code. This is where loops set in, they are constructs used to tell a program to run a particular block of code for as long as a condition remains true. Much like as long as you're still alive you must be breathing and if you're not alive then you can't breathe. There are three main type of looping constructs

  • For loops
  • While loops
  • Do loops

For Loop

A for loop is used to iterate (repeat) a block of code for as long as a condition evaluate to true. let's look at syntax of a for loop in JavaScript.

for(starter; condition; modifyStarter){
//repeat task
}
Enter fullscreen mode Exit fullscreen mode

The first thing we pass into the for loop is a starter counter, this is a variable which represents the initial condition upon which the iteration is to begin, this starter counter must always evaluate to true or else it will not run, we put a semi colon and then we pass the next argument which is a condition to check against after the initial iteration of the loop, if this condition evaluate to true the loop will run again, and then it will still check the condition (our second argument) if it is true, and then it will iterate again, each time our block of code is iterated, the condition is evaluated and as long as it is true the code will iterate again. However if it evaluates to false, then our code will not be iterated. This is important so that our code doesn't get trapped in an endless loop. The third argument we need to pass is a statement that will modify the state of the starter counter, this way we ensure that our starter doesn't remain constant and is actually changing each time our code is iterated. Hope this makes sense, lets see an example

//print 1 to 5
for(var i = 0; i < 6; i++){
console.log(i)
}
//prints out 012345
Enter fullscreen mode Exit fullscreen mode

Our starter counter here is i and we set it to zero initially, the next argument was our condition which is "i < 6" this simply tells the compiler that as long as i < 6 repeat the process. The third argument here is the modify stater that is we are telling the compiler to increase the value of i by one after each iteration of the code.
That is why we first get 0 logged to the console, because our starter began at 0. We get 5 last but not 6 because our condition said that i should be less than 6. And we see that after 0, we get 12345 logged to the console because after 0 our modifyStarter has actually incremented i by 1 and so on and so forth.
We can also redo this example such that we get 5,4,3,2,1,0 instead of the ascending order we used in the first example.

for(var i = 5; i >=0; i--){
console.log(i)
//prints 543210
}
Enter fullscreen mode Exit fullscreen mode

It is still the same logic, here our starter is 5, our condition is i should be greater than or equal to 0, our modify starter here reduces the value of I by 1 after each iteration of the code. So it starts from 5 and iterates till 0 and then stops.
We can use this method anytime we are sure of a definite amount of time we want to iterate a process, even if we are unsure too, the key here is that after a particular number of time, our code should stop repeating itself or it should repeat itselft for a number of time, till our condition evaluates to false.
This allows us to loop through arrays and do something with the items inside the array. Let's look at an example;

var myArr = [1,2,3,5,8,13]
// looping through the array
// to get the Fibonacci numbers
for(let i =0; i < myArr.length; i++){
    console.log(myArr[i])
}

// prints out 1, 2, 3, 5, 8, 13
Enter fullscreen mode Exit fullscreen mode

We tell the loop that as long as i is less that the number of items inside an array, the way we get the number of items in an array is through the array.length and this returns to us a number, lastly we tell the loop that i should be incremented by 1 after each iteration. Inside the body of the loop, to actually get each item's value in the array we use the index method, remember we use array[index] to get or set the value of an item at a particular position in the array.

var myArr = []
myArr[0] = 1;
console.log(myArr[0])
prints out 1
Enter fullscreen mode Exit fullscreen mode

following from that we used this index method and we printed to the console the item at the the index 'i' where i = a number, at each iteration of the loop. When the loop iterates for the first time we get 1 printed out because i = 0, and 1 is the first item in the array with an index of 0. now i is incremented by one, our loop then evaluates the value of i against the length of the array, i is less than it, it runs again. we get 2 printed out because i is now 1, and the item at index position of 1 is 2, the second item follows up. We can reverse this condition and print from the bottom of the array to the top of the array. However if you are working with arrays, i'd rather have you use the forEach method. The syntax is easier and neater.

Controlling the loop

If we want explicit control of when a loop ends or maybe we want to exit out of a loop prematurely, we can do the following with a for loop to gain mor control.

for(let i =0; i< 10;i++)
{
    if(i >= 4){
        break;
    }
    else{
        console.log(i)
    }

}
Enter fullscreen mode Exit fullscreen mode

We use the break statement to break out of a loop upon a certain condition. in our example we say if i is greater than or equal to 4 we the interpreter should break out of the loop we can also use the return statement instead of break. We can also use the continue statement inside a loop to do something else for a particular value of i instead of the traditional code we expected to run, lets look at an example.

for(let i =0; i< 6;i++)
{

    if(i == 4){
        console.log('it is number 4')
        continue
    }
    console.log(i)

}


// prints out 1, 2, 3, it is number 4, 5
Enter fullscreen mode Exit fullscreen mode

We see here that instead of 4 being logged out we log out it is number 4, rather than just this crude examples we could be doing more complex computation.

For of

We can use a modification of the for loop to print out values from an iterable object like an array, map, iterators, nodelists to access the values stored inside the iterable object. it is simpler and more cleaner than using the normal for loop. let's see an example

// STYNTAX
for(value of iterableObject){
    // do something value
}

var myArr = [2,4,5,6,3,1]

for(v of myArr){
    console.log(v)
}
// prints out
// 2, 4, 5, 6, 3, 1
Enter fullscreen mode Exit fullscreen mode

For in

We can also iterate over normal objects using a slightly modified version of the for loop, we use a for in loop, that is loop through each key in the object and do something.

// STYNTAX
for(key in object){
// do something with key or
object[key] //this gives us 
// to the value of the current key the pointer is at
}

var myObj = {name: 'John Doe', job: 'coding', age: 23}

for(key in myObj){
    console.log(`${key} - ${myObj[key]}`)
}
// prints out
// name - John Doe
// job - coding
// age - 23
Enter fullscreen mode Exit fullscreen mode

So do try some examples to wrap your head around it, that is it for this article, next we will be looking at while and do loops.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .