What are loops?
Loops are used in programming to run repeated logic based on a specific condition. Loops will continue to run as long as the condition is true and when the condition becomes false that's when the loop stops. In this article I will explain for loops, while loops, for in loops, infinite loops and for of loops. I will also explain how we can loop over arrays and objects. Let us begin:
For loop
We use for loops when we know how many times we're going to loop for. The syntax for for loops is pretty simple. We have an initial expression then the condition then increment expression. if this sounds confusing don't worry I'll be providing examples below.
Example 1
for(let i = 0; i <= 10; i++){
console.log(i);
}
In the above example we want the loop to run until the condition is met(I IS LESS THAN OR EQUAL TO 10) then we increment by 1 each time the loop runs which is what i++ means. We do this until the condition in the loop is false and the loop stops. The variable i could be anything but it is industry practice to just use i.
Example 2
for(let i = 300; i >= 0; i -=50){
console.log(i);
}
In this example our starting point in the loop is 300, as long as the variable i is greater than or equal to 0 we subtract by 50 as seen in the increment part of the loop.
Looping over arrays and objects with for loops
When we loop over arrays with for loops we always start at 0. In the examples below I'll work through the syntax and the logic behind it.
Example 3
const examScores = [70, 67, 89, 78, 90];
for(let i = 0; i < examScores.length; i++){
console.log(i, examScores[i]);
};
In this example we are printing the game scores along with their specific index in the array. In the condition section we use the method length because we don't want to hard code the length of the array.
Example 4
const gameScores = [
{
playerName: 'jacky',
score: 34
},
{
playerName: 'jacky',
score: 76
},
{
playerName: 'phil',
score: 90
},
{
playerName: 'luke',
score: 68
},
];
for(let i = 0; i < gameScores.length; i++){
let gamePlayScore = gameScores[i];
console.log(`${gamePlayScore.playerName} score is ${gamePlayScore.score}`)
}
In the example above we are looping through both an array and an object. We created the gamePlayScore to directly dive into the array gameScores. Then we use template literals to print out the players name and their score.
Looping through strings
Looping throughs strings is essentially the same process. In the example below I'll show you how to do this.
Example 5
const atlas = 'mexico';
for(let i = 0; i <= atlas.length; i++){
console.log(atlas[i]);
};
Nested for loops
With nested for loops every time the outer loop runs the inner loop completes its full cycle. In the example below I will demonstrate how we write the syntax for this:
Example 5
for (let i = 0; i <= 10; i++){
console.log('Outer: ', i);
for (let j = 10; j >= 0; j -= 2){
console.log('Inner: ', j);
}
}
In this example each time the outer loop runs the inner loops completes is full cycle by deducting 2 from 10. This will continue until the the cycle for the outer loop is finished.
For of loops
We use for of loops when we don't care about about indices or accessing the array by the number. For of loops are not supported by internet explorer, just a word of warning. In the example below I will show you how to use for of loops while looping over an array and a string.
Example 6
let oceans = ['pacific', 'atlantic', 'indian ocean', 'artic ocean', 'southern' ];
for(let char of oceans){
console.log(char)
}
The code snippet above will allow you to print everything in the array. We declare the variable let char so each time the loop iterates it gets assigned a different value. The variable can be named whatever you want it just needs to make sense. The oceans variable properties are the ones that are getting iterated. console.log(char) prints out the results each time loop iterates.
Example 7
for(let char of 'andrew james'){
console.log(char.toUpperCase());
}
In this example we're using the for of loop to loop over the string and then using the method toUpperCase() to print the string in upper case letters.
For of loops with objects
Objects are not iterable so we use Object.keys() which returns the keys of the object. I'll show you what I mean in the example below.
Example 8
const midTermGrades = {
Asa: 45,
Bilal: 35,
Buhari: 43,
Oluwa: 29
};
for (let grades of Object.keys(midTermGrades)){
console.log(grades)
}
In this example Object.keys() allows us to get the keys of the object.
For in loops
For in loops allows us to loop over an object without using Objects.keys(). The syntax is pretty simple to understand, I'll show you below.
const animalWeightLbs = {
Lion : 570,
Hippo: 9000,
Gorilla: 500
};
for(let char in animalWeightLbs){
console.log(char);
}
As you've seen above for in loops allow us to loop over objects without any additional methods, this is one way in which it differs from for of loops.
While loops
We usually use while loops when we don't know exactly how many times we're going to run a loop for. The syntax differs from for loops in a number of ways. One of the most significant differences to me is the fact that we have to set a counter when we're using a while loop. I'm going to show the syntax for for loops below.
Example 9
let j = 0;
while(j <= 5){
console.log(j);
j++;
In this example we set the variable j to equal 0. We then run the while syntax, as long as j is less than or equal to 5 we are going to add one.
Infinite loops
You don't ever want to write infinite loops, they'll run until your browser starts to malfunction, Infinite loops are loops that never manage to meet a condition so the go on and on and because there is no condition to be met they never stop. The first time I wrote an infinite loop I had to close the browser and even that took a while to execute.
Conclusion
Loops are fundamental to every programming language you'll come across, they allow us to save time when we're writing code which is always a positive for programmers. I hope this tutorial cleared up any issues you were having with loops.