paint-brush
JavaScript Loops for Beginners: Learn the Basicsby@hacker-mgqp1lu
496 reads
496 reads

JavaScript Loops for Beginners: Learn the Basics

by July 6th, 2024
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

To perform repeated tasks in JavaScript can be a lot of work and time-consuming. Loops provide an excellent way to solve this problem as they help reduce code repetitiveness, thereby shortening code length. In this article, we will learn what loops are, the different types of loops, how they work, and best practices to consider when using a loop.
featured image - JavaScript Loops for Beginners: Learn the Basics
undefined HackerNoon profile picture

It's a gloomy Monday, and you're at work. We all know how depressing Mondays can be, right? Your boss approaches you and says, Your boss approaches you and says, 'Hey, we have 300 unopened emails from the weekend. Please open each one, write down the sender's name, and delete them after you're done.


This task seems very tedious if done manually. The next thing on your mind is probably to get on Google and look for software that can automate this process and make your life easier, right?


Well, we have similar situations in programming. There are times when you need to perform repeated tasks until they're done. How do you address this issue? In JavaScript, we have what we refer to as loops. Loops help us handle repetitive tasks by minimizing the amount of code required to complete the task.


In this article, we'll discuss what a loop is, how it works, and the various methods we can use to apply it in our programs.

What Is a Loop?

Loops are used in JavaScript to perform repeated actions easily. They are based on a condition that returns true or false.


A condition is an expression that must be satisfied for a loop to continue running. A loop executes as long as the specified conditions returns true and stops when it returns false.

When Do You Need to Use a Loop?

Loops are useful for carrying out repetitive tasks. For example, using a loop shortens the code needed to solve a problem. It saves time, optimizes memory usage, and improves flexibility.


The true significance of loops extends beyond reducing code length and repetition. They also help when working with data in an array, object, or other structures. Additionally, loops enhance code modularity by reducing repetition and increasing reusability, allowing code to be utilized in various parts of a project.

Types of Loops

Loops can be categorized into two main types: entry-controlled loops and exit-controlled loops.

Entry-controlled loops evaluate the condition at the "start of the loop" before the loop's body is executed. If the condition is met, the body runs; otherwise, it doesn't. Examples of entry-controlled loops include the for and while loops.

Exit-controlled loops emphasize running the loop's body at least once before checking the condition, ensuring that the loop's body executes before the condition is evaluated. The do-while loop is a prime example of an exit-controlled loop.

Let's examine some examples of entry-controlled loops:

While Loop

A while loop refers to a loop type that continues to execute the code within its body as long as the specified condition returns a true value.

while (condition) {
  //  loop's body
}

The following list explains the functionality of a while loop:


  1. The while loop takes a test condition inside parentheses.


  2. The program checks the condition to see whether it passes or fails.


  3. The code within the loop's body executes as long as the condition is passed.


  4. The program terminates its operation once the test condition fails.

While Loop Flowchart


Below, let's take a practical example of the while loop:

let arr = [];
let i = 1;
let number = 5;
 
while (i <= number) {
arr.push(i)
i++
}

console.log(arr)
  1. The code snippet above initializes the "arr", "i", and "num" variables.


  2. The "arr" variable is an array that holds the values that pass the test condition.


  3. The "i" variable keeps track of each increment after each iteration.


  4. The "number" variable compares the value of "i" to it value (5) after each iteration.


  5. The code within the loop's body pushes each value of "i" after each iteration into the array as long as "i" is less than or equal to "number".

  6. Once the current value of "i" fails the condition, in this case, where the value of "i" is greater than "number" which is 6, the loop stops running.


    The push() method is a built-in JavaScript function that adds a new item to the end of an array.


Output

[1, 2, 3, 4, 5]

do-while Loop

A do-while loop closely resembles the while loop; the main difference between the while and the do-while loop is that the do-while loop ensures code execution at least once before evaluating the loop's condition; the do-while loop has the following syntax below.

Do-While Loop Flowchart


The do-while loop has the following syntax:


do {
  // loop's body
}
while (//condition)

The do-while is an excellent example of an exit-controlled loop. This lies in the fact that exit-controlled loops give priority to the loop's body before the test condition, now let's delve into a practical code example utilizing the do-while loop.


Example:

let i = 1;
let num = 5;

do {
  console.log(i);
  i++;
} while (i <= num);

Now, let's break down this code snippet:


  1. We initialized the "i" and "num" variables.


  2. The console logs in the value of "i" (1) before evaluating the loop's condition.


  3. The condition is checked, and the value of "i" increments with +1 after each iteration.


  4. The loop ends its operation once "i" is greater than "num".


Output

1
2
3
4
5


Although the do-while loop is very much similar to the while loop, there are subtle differences we must note; let’s take another example that compares the difference between the while and do-while loop.

let i = 5;
let num = 4

while( i < num)
{
  console.log(i)
}

This while loop above won't return any result to the console; now, why is this so?


  1. We initialized the "i" and "num" variables with values of 5 and 4, respectively.


  2. The condition checks if the value of "i" is less than "num".


  3. If true, it logs in each respective value.


  4. Since the initial value of "i" exceeds that of "num", the loop never runs.


Now, let's take a similar example with the do-while loop.

let i = 5;
let num = 4;

do {
  console.log(i)
}
while ( i < num)


Output

5

The do-while loop ensures the execution of the code block, which returns 5 into the console, although "i" has a higher value than "num" initially, it's still logged in the console once. This representation shows you the difference in functionality between the do-while and while loop.

For Loop

The for loop is a unique type of loop and one of the most commonly used loop by programmers, It runs a code block a specific number of times depending on a condition. The for loop has the following syntax:

for (Expression1...; Expression2....; Expression3...{
     //code block
}

Expression 1: This part of a for loop is also known as the initialization area; it's the beginning of our for loop and the area where the counter variable is defined. The counter variable is used to track the number of times the loop runs and store that as a value.


Expression 2: This is the second part of the loop; this part defines the conditional statement that would execute the loop.


Expression 3: This is where the loop ends; the counter variable in this section updates its value after each iteration either by increasing or decreasing the value as specified in the condition.

For Loop Flowchart



Let's dive into an example using the for loop.


for (let i = 0; i < 100; i++) {
    console.log("Hello World" )
}

From the code snippet above, let's break it down together.


  1. First, we've initialized the counter variable "i" with a value of zero.


  2. Next, we've created the conditional statement that would keep the code running.


  3. We compared the value of "i" with 100; if it passes this test, "Hello World" is logged.


  4. This process repeats while the counter increases with +1 after each iteration.


  5. The loop ends once the counter's value reaches 100.


Output

Hello World
Hello World
Hello World

...

//repeated 97 more times making it 100 "Hello World" in total
...


for-each loop

The for-each loop is a method in JavaScript that travels through an array and applies a callback function on each element in that array; a callback function is simply another function passed as a parameter into a function. The callback function works by running sequentially after the main function is done executing.


Let's examine the basic syntax of a for-each loop.

array.forEach(function(currentValue, index, arr))


The provided code above explains the workings of a for-each loop.


  • This loop accepts three parameters, which are the current value, an index, and an array.


  • The current value represents the present value of the element in the array.


  • The index is an optional parameter that tells you the numbered position of the current element in that array.


  • The arr is another optional parameter that tells you what array the element belongs to.


let myArray = [1, 2, 3, 4, 5];

array.forEach((num, index, arr) => {
  arr[index] = num * 2;

  console.log(array);
});

Let's break down the example above:


  1. We initialized an array with the variable name "myArray" and stored it with integers ranging from 1 to 5.


  2. The for-each array method takes three parameters and applies a callback function on the array.


  3. This line; arr[index] = num * 2 multiplies the value of the current element by 2 and assigns the returned value to the current element's index.


Take note: the for-each array method does not return a new array; rather, it modifies the original array and returns it.


Output

[2, 4, 6, 8, 10]

What Are For... In and For... of Loops in JavaScript?

The for... in and for... of loops are very useful when it comes to iterating over iterable objects; iterable objects refer to any element that is capable of being looped over, common examples of iterable objects are arrays, strings, sets, etc.


The for... in and for... of are similar in how they iterate/move through objects, the main difference between them is shown in how they return values.

for... in Loops

A for... in loop is useful when you need to extract the key(s)/properties from an object and its corresponding properties from the parent object. The for... in loop at times might iterate through an object in a manner that is different from the way it was defined in that particular object; let's take an example of a for... in loop in action.

let namesArray = [];

const studentScores = {
John: 60,
Dan: 53,
Tricia: 73,
Jamal: 45,
Jane: 52
}

for(const name in studentScores){
  namesArray.push(name);
}

console.log(namesArray);

In the example above, we have defined an object named studentScores that contains several student names and their corresponding scores. By using for... in, we were able to retrieve only the names of the students, which represent the keys of the object studentScores, and store them in an array by using the push() method.


Output

["John", "Dan", "Tricia", "Jamal", "Jane"]

for... of Loops

The for... of loop is a special type of loop that iterates over the values of iterable objects such as arrays, strings, maps, etc., for... of loops do not concern themselves with the keys or properties of an object, rather they show priorities on the values only.


The for... of loop is unable to iterate over regular objects and will throw an error since they are not iterable. Let's take an example using the for.. of loop.

let numArray = [1,2,3,4,5]

for (const value of numArray) {
    console.log(value)
}

// Output =  1,2,3,4,5

In summary, the for... in and for... of loops are a great way to loop through iterable objects; the main difference is a for... in loop returns the key of an Object while the for... of loop returns only the values of iterable objects.

What Is an Infinite Loop, and How Can We Avoid It?

An infinite loop is a loop that persists indefinitely because it lacks a well-defined exit condition. Such loops can be dangerous, potentially crashing your browser and causing unintended actions in your program.

// infinite loop sample
while (true) {
 console.log("keep on running")
}

To prevent infinite loops in your program, always ensure that there is an exit condition defined within your loop.

Conclusion

Thank you very much for getting to the end of this article, loops in Javascript are an important concept every developer needs to master as it is very valuable to creating a good and optimizable program. I believe with this article you will be able to understand the basics and intricacies of using loops in your program.