Loops In JavaScript
zachmarullo
Posted on August 11, 2022
In JavaScript, there are several different kinds of loops that can be used to accomplish whatever task you may have. These range from iterating through an array, to having a loop execute a task a certain number of times. Loops can come in handy in a lot of different ways, from checking through a database for a name, to running a task repetitively in a video game you are creating.
What is a loop?
Loops are used to run blocks of code repetitively until a certain criteria is met. At this point, the loop will cease execution and move on to the next part of your code.
For Loops:
For loops are used to iterate through arrays. They can be combined with conditional "if" statements to pick out pieces of an array and return them to you, or simply to build out something in the console, such as a triangle made out of pound symbols(#).
Here's an example of creating a triangle:
function createTri(num) {
for (let i = '!'; i.length <= num; i+='!') {
console.log(i);
}
}
console.log(createTri(5));
The output for this triangle would look like this:
! //first iteration of loop
!! //second iteration of loop
!!! //third iteration of loop
!!!! //fourth iteration of loop
!!!!! //fifth iteration of loop
At this point, the loop would see that it has met its criteria and break out of the for loop because the length of "i" has become equal to the number passed into the function. In this case, the number was 5.
For loops can also be used to iterate through arrays and return values depending on how the loop is set up.
Here's another example of a for loop which will be explained afterwards:
const arr = [1, 2, 3, 4, 5, 6];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
for (let j = 1; j < arr.length; j+=2) {
console.log(arr[j]);
}
For the first example, in each iteration of the for loop, "i" represents the index number, and console logging "arr[i]" on each iteration will print each value of the array to the console because the loop is only going to stop when reaching the end of the array(or "arr.length" in this case).
In the second example, notice "i" is set to 1. This is because, like mentioned above, the value of "i" is being taken from the index rather than its actual position in the array. This means that the second loop in the above example will only print 2, 4, 6 (the even numbers). The same would be true to print the odd numbers if "i" were set equal to zero, because it would log the values of "i" at index 0, 2, and 4. This would produce the result of 1, 3, and 5.
For-in loops:
For/in loops are used to iterate over the contents of an object. It is important to note that for/in loops can also iterate over the contents of an array, but should not be used if the order of the array contents are important.
Below is an example of looping through an object, I'll use the object "MNF".
First we will go through looping and logging the key names to the console, and then we will log the values of those keys.
let MNF = {
firstName: "Marilyn",
middleName: "Nicole",
lastName: "Foster"
}
for (let key in MNF) {
console.log(key);
}
// this prints firstName, middleName, lastName to the console.
let MNF = {
firstName: "Marilyn",
middleName: "Nicole",
lastName: "Foster"
}
for (let key in MNF) {
console.log(MNF[key]);
}
/* this example will print the actual value
of the keys to the console, producing:
Marilyn Nicole Foster
*/
While Loops
While loops are created to execute a specific block of code over and over as long as the test condition evaluates to true. It is important to note that in a while loop the test condition is evaluated each iteration before execution.
let text = "";
let i = 0;
while (i < 10) {
text += "The number is " + i + "\n";
i++;
}
console.log(text);
Above, this code will only run until it hits "The number is 9" because before it runs the code in the body, it can see that the number has reached 10 after iterating and therefore breaks out of the loop.
In conclusion, as you learn to code, you are introduced to new methods, which can have the same effect that loops will without having to insert all of the pieces manually, but it's important to understand how the foundation of each method works. This is the reason loops are so important to understand when trying to increase your knowledge and ability to do more with less code.
Posted on August 11, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.