
JavaScript Loops: for, while, forEach Explained in Code | SBT
Loops are one of the most essential building blocks in JavaScript. They allow you to repeat actions efficiently, making your code cleaner and more powerful. Whether you're iterating through arrays or performing repeated tasks, understanding how each type of loop works will sharpen your JavaScript skills.
In this blog, we’ll explore the for, while, and forEach loops with clear explanations and code examples using the string "Sudip".
1. The for Loop
One of the most popular loops in JavaScript is the for loop, particularly when the number of iterations is known ahead of time. An initialisation, a condition, and an increment or update statement make up its three components. This loop is perfect for iterating over items in an ordered collection, such as an array or string, or for repeating an action a predetermined number of times.
Let’s examine a simple example:
const name = "Sudip"; for (let i = 0; i < name.length; i++) { console.log(name[i]); }
- The string "Sudip" is assigned to the variable name in this code. A counter variable i is initialized with the value 0 at the beginning of the for loop.
- The condition i < name.length checks whether i is less than the total number of characters in the string. If the condition is true, the loop body executes.
- Inside the loop, console.log(name[i]) prints the character at the current index. As a result, one character from the string is printed during each iteration.
- After every iteration, the expression i++ increments the value of i by 1, allowing the loop to move to the next character.
- When i becomes equal to the length of the string, the condition becomes false, and the loop terminates. The result will be:
S u d i p
Now let’s look at the same example using a different name:
const name = "Gourab"; for (let i = 0; i < name.length; i++) { console.log(name[i]); }
This loop works in exactly the same way as the previous one, but it prints each character of the string "Gourab":
G o u r a b
To demonstrate a more complex use case of the for loop, let’s consider a scenario involving numbers:
let sum = 0; for (let i = 10; i <= 99; i++) { if (i % 2 === 0) { sum += i; } } console.log("Sum of all even numbers from 10 to 99 is:", sum);
- In this example, we are using a for loop to calculate the sum of all even numbers between 10 and 99.
- The loop starts at i = 10 and continues as long as i <= 99. After each iteration, i is incremented by 1.
- Inside the loop, we use the condition i % 2 === 0 to check whether the current number is even. If the condition is true, the value of i is added to the sum.
- After the loop has processed all numbers in the range, the total sum of all even numbers between 10 and 99 is printed. The output will be:
Sum of all even numbers from 10 to 99 is: 2444
2. The while Loop
The while loop is used in JavaScript to execute a block of code repeatedly as long as the given condition remains true. Unlike the for loop, which is often used when the number of iterations is known, the while loop is preferred in situations where the loop might continue based on a dynamic condition. This makes it especially suitable for input-driven programs, data validation, or scenarios involving user interaction or unpredictable data sets.
Let’s begin with a simple example using a string:
const name = "Sudip"; let i = 0; while (i < name.length) { console.log(name[i]); i++; }
- In this code, we declare a variable name with the value "Sudip". We then initialize a counter variable i with 0.
- The loop will execute as long as the condition i < name.length is true. Since the length of the string is 5, the loop will execute five times.
- Inside the loop, name[i] accesses the character at the current index i, and console.log prints it.
- After printing, we increment the counter i using i++ so that the loop progresses toward its stopping point.
- The loop stops automatically once i equals 5, and all characters of the string are printed one after another:
S u d i p
Now, let’s look at a more complex example using numbers:
let number = 123456789; let sum = 0; while (number > 0) { let digit = number % 10; sum += digit; number = Math.floor(number / 10); } console.log("Sum of digits:", sum);
- In this example, we are trying to find the sum of the digits of a number. We start with the number 123456789 and initialize a variable sum with 0 to keep track of the cumulative sum of digits.
- The loop runs as long as number > 0. This means the loop continues until all digits have been processed.
- Inside the loop, we use the modulus operator (% 10) to extract the last digit of the number. For example, 123456789 % 10 gives 9.
- We then add this digit to the sum variable.
- Next, we use Math.floor(number / 10) to remove the last digit from the number. So 123456789 / 10 becomes 12345678.9, and Math.floor converts it to 12345678.
- This process continues, digit by digit, until the number becomes 0.
- Finally, console.log prints the sum of the digits, which for 123456789 is:
Sum of digits: 45
3. The forEach Method
The forEach method is a modern and readable way to iterate over elements in an array. Unlike the for and while loops, forEach is a method that belongs to arrays in JavaScript. It is particularly useful when you want to perform an action for each element in an array without manually handling the loop counter or managing loop conditions. The forEach method accepts a callback function that gets executed for every item in the array, making the code more concise and expressive.
Let’s start with a simple example using the name "Mondarlo":
const nameArray = ["M", "o", "n", "d", "a", "r", "l", "o"]; nameArray.forEach(function(letter, index) { console.log(`Index ${index}: ${letter}`); });
- In this example, we first define an array called nameArray that contains each character of the string "Mondarlo" as individual elements.
- The forEach method is called on the array, and it receives a callback function. This function has two parameters: letter and index. The letter represents the current value being processed in the array, while index represents the position of that value within the array.
- Inside the callback, console.log is used to print both the index and the corresponding letter in a formatted string.
- The output will be:
Index 0: M Index 1: o Index 2: n Index 3: d Index 4: a Index 5: r Index 6: l Index 7: o
This shows how forEach simplifies the iteration by directly giving you access to both the value and its index without needing to manage a counter variable manually.
Now let’s look at a more complex example using an array of numbers:
const numbers = [12, 45, 67, 89, 34, 22, 90]; let evenSum = 0; let oddCount = 0; numbers.forEach(function(num) { if (num % 2 === 0) { evenSum += num; } else { oddCount++; } }); console.log("Sum of even numbers:", evenSum); console.log("Count of odd numbers:", oddCount);
- In this example, we have an array of numbers. The goal is to calculate the sum of all even numbers and count how many odd numbers are present.
- The forEach method processes each number in the array. Inside the callback, we check whether the number is even using the condition num % 2 === 0.
- If the number is even, we add it to the evenSum. If it is odd, we increase the oddCount by 1.
- After the loop finishes, we print the total sum of even numbers and the count of odd numbers. The output will be:
Sum of even numbers: 158 Count of odd numbers: 3
Concluding
In JavaScript, choosing the appropriate loop type goes beyond syntax—it's about selecting the structure that best supports your code's readability, logic, and purpose. Each type of loop has its own strengths, and understanding when to use each one is essential for writing efficient, maintainable, and user-friendly programs.
The for loop is ideal when you know in advance how many times the loop should run. It is especially useful when working with indexes, numeric counters, or tasks that need to be executed a fixed number of times. For example, a for loop is well-suited for iterating through the characters of a string like "Sudip" or generating a sequence from 1 to 100.
The while loop is best used when the number of iterations is unknown and depends on a changing condition. It provides flexibility for situations where the loop should continue until a specific logical state is met. Common use cases include waiting for user input, reading data until a certain value is reached, or processing information until an external event occurs.
The forEach method is a clean and modern approach for working with arrays. It removes the need to manually manage loop counters or boundary conditions and is ideal when you want to apply an action to every element in an array. Whether you're printing each letter of a name like "Mondarlo" or processing a list of numbers, forEach makes the code more expressive and readable.
Ultimately, mastering these loop structures will help you write clearer, more reliable JavaScript code—whether you're working with simple strings or building complex applications.
0 Comments