JavaScript Mastery - Loops


1.Loops
Loops enable repetitive execution of code blocks, essential for operations like data processing, iteration, and automation in JavaScript applications.
1.1 for Loop
The for loop is a powerful control structure that executes code a predetermined number of times. It's the go-to loop when you know exactly how many iterations you need, making it perfect for array operations and counting.
Where to use in real life:
Iterating through arrays or collections of known length
Generating sequential data like calendar dates
Creating repetitive UI elements like table rows
Syntax:
for (initialization; condition; final-expression) {
// code block
}
Examples:
// Example 1: Generating a multiplication table
let multiplier = 7;
for (let i = 1; i <= 5; i++) {
let result = multiplier * i;
console.log(`Code Subtle's multiplication table: ${multiplier} × ${i} = ${result}`);
}
/* Output:
Code Subtle's multiplication table: 7 × 1 = 7
Code Subtle's multiplication table: 7 × 2 = 14
Code Subtle's multiplication table: 7 × 3 = 21
Code Subtle's multiplication table: 7 × 4 = 28
Code Subtle's multiplication table: 7 × 5 = 35
*/
// Example 2: Calculating factorial
let number = 5;
let factorial = 1;
for (let i = 1; i <= number; i++) {
factorial *= i;
console.log(`Code Subtle's factorial calculation step ${i}: ${factorial}`);
}
/* Output:
Code Subtle's factorial calculation step 1: 1
Code Subtle's factorial calculation step 2: 2
Code Subtle's factorial calculation step 3: 6
Code Subtle's factorial calculation step 4: 24
Code Subtle's factorial calculation step 5: 120
*/
// Example 3: sum = 1*2 + 2*3 + 3*4.......9*10 --> i*(i+1)
let num = Number(prompt('enter the number'))
let sum=0
for( let i=0; i<10; i++){
sum = sum + i*(i+1)
console.log(sum, i + "*" +(i+1));
}
/* Output:
0 0*1
2 1*2
8 2*3
20 3*4
40 4*5
70 5*6
112 6*7
168 7*8
240 8*9
330 9*10
*/
Tips & Tricks:
Use let for loop counter variables to keep them properly scoped within the loop
For better performance when iterating arrays, cache the array length in a variable
You can omit any of the three expressions in a for loop, creating more flexible loop patterns
1.2 while Loop
The while loop is a fundamental control structure that repeatedly executes code while a specified condition remains true. It's particularly useful when the number of iterations isn't known in advance and depends on dynamic conditions.
Where to use in real life:
Reading data until reaching EOF (end of file)
Processing user input until a valid response is received
Animation loops that continue until a specific event occurs
Syntax:
while (condition) {
// code block
}
Examples:
// Example 1: print multiplication table
let i = 1, num=10
while(i<=10){
console.log(num+ " * " +i+ " = "+num*i);
i++;
}
/* Output:
10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
10 * 10 = 100
*/
// Example 2: Sum = 1*3 + 2*4 + 3*5..... +9*11
let i = 1,
sum = 0;
while (i <= 9) {
sum = sum + i * (i + 2);
console.log(i + " * " + (i + 2) +" = "+ i*(i+2));
i++;
}
/* Output:
1 * 3 = 3
2 * 4 = 8
3 * 5 = 15
4 * 6 = 24
5 * 7 = 35
6 * 8 = 48
7 * 9 = 63
8 * 10 = 80
9 * 11 = 99
*/
// Example 3: Perfect Number or not
let i = 0, sum = 0
let num = Number(prompt("Enter the number: "))
while(i<num){
if(num%i==0){
sum = sum + i
}
i++
}
if(num===sum){
console.log("The number is perfect number: ",num)
}
else{
console.log("The number is not a perfect number: ",num)
}
/* Output:
The number is perfect number: 28
*/
Tips & Tricks:
Always ensure your condition will eventually become false to prevent infinite loops
Consider using a loop counter with a maximum value as a safety mechanism
For simple accumulation or processing that depends on a condition, while loops often read more naturally than for loops
1.3 do...while Loop
The do...while loop guarantees at least one execution of the code block before checking the condition. This unique characteristic makes it perfect for scenarios where you need to ensure code runs once regardless of the condition.
Where to use in real life:
Input validation where you must collect input at least once
Menu systems that should display options before checking if the user wants to exit
Game loops where one round should always be played
Syntax:
do {
// code block
} while (condition);
Examples:
// 1. SUM OF DIGITS
// Function to calculate sum of digits using do-while loop
function sumOfDigits(number) {
let num = Math.abs(number); // Handle negative numbers
let sum = 0;
do {
sum += num % 10; // Add last digit to sum
num = Math.floor(num / 10); // Remove last digit
} while (num > 0);
return sum;
}
// Test sum of digits
console.log("=== SUM OF DIGITS ===");
console.log(`Sum of digits of 1234: ${sumOfDigits(1234)}`); // Output: 10
console.log(`Sum of digits of 9876: ${sumOfDigits(9876)}`); // Output: 30
console.log(`Sum of digits of 555: ${sumOfDigits(555)}`); // Output: 15
console.log(`Sum of digits of 0: ${sumOfDigits(0)}`); // Output: 0
console.log(`Sum of digits of -456: ${sumOfDigits(-456)}`); // Output: 15
// ==========================================
// 2. REVERSE OF NUMBER
// Function to reverse a number using do-while loop
function reverseNumber(number) {
let num = Math.abs(number); // Handle negative numbers
let reversed = 0;
do {
reversed = reversed * 10 + (num % 10); // Build reversed number
num = Math.floor(num / 10); // Remove last digit
} while (num > 0);
// Return with original sign
return number < 0 ? -reversed : reversed;
}
// Test reverse number
console.log("\n=== REVERSE OF NUMBER ===");
console.log(`Reverse of 1234: ${reverseNumber(1234)}`); // Output: 4321
console.log(`Reverse of 9876: ${reverseNumber(9876)}`); // Output: 6789
console.log(`Reverse of 1200: ${reverseNumber(1200)}`); // Output: 21
console.log(`Reverse of 0: ${reverseNumber(0)}`); // Output: 0
console.log(`Reverse of -456: ${reverseNumber(-456)}`); // Output: -654
// ==========================================
Tips & Tricks:
The do...while loop is ideal for input validation where you must process at least one attempt
Be careful with potential infinite loops; include a fail-safe exit condition if needed
Consider using do...while over while when you want to separate the first execution from subsequent ones logically
2. Loop Control Statements
Loop control statements provide mechanisms to alter the normal flow of loops, giving you more precise control over execution.
2.1 break Statement
The break statement terminates the current loop and transfers control to the statement following the loop. It allows you to exit a loop early when a certain condition is met, preventing unnecessary iterations.
Where to use in real life:
Search algorithms that can stop once a target is found
Input validation when an unrecoverable error is detected
Early exit from data processing when a threshold is reached
Syntax:
break;
Examples:
// Example 1: Finding an element in an array
let users = ["Alex", "Jamie", "Taylor", "Morgan", "Casey"];
let targetUser = "Taylor";
console.log(`Code Subtle searching for user: ${targetUser}`);
for (let i = 0; i < users.length; i++) {
console.log(`Code Subtle checking position ${i}: ${users[i]}`);
if (users[i] === targetUser) {
console.log(`Code Subtle found target user at position ${i}`);
break;
}
}
/* Output:
Code Subtle searching for user: Taylor
Code Subtle checking position 0: Alex
Code Subtle checking position 1: Jamie
Code Subtle checking position 2: Taylor
Code Subtle found target user at position 2
*/
// Example 2: Input validation with early exit
let inputs = ["valid", "invalid", "error", "valid"];
console.log("Code Subtle starting validation process");
for (let input of inputs) {
console.log(`Code Subtle validating: "${input}"`);
if (input === "error") {
console.log(`Code Subtle encountered critical error, stopping validation`);
break;
}
console.log(`Code Subtle processed: "${input}" successfully`);
}
console.log("Code Subtle validation process completed");
/* Output:
Code Subtle starting validation process
Code Subtle validating: "valid"
Code Subtle processed: "valid" successfully
Code Subtle validating: "invalid"
Code Subtle processed: "invalid" successfully
Code Subtle validating: "error"
Code Subtle encountered critical error, stopping validation
Code Subtle validation process completed
*/
// Example 3: Database query simulation with result limit
let databaseRecords = [
{id: 1, name: "Record 1"},
{id: 2, name: "Record 2"},
{id: 3, name: "Record 3"},
{id: 4, name: "Record 4"},
{id: 5, name: "Record 5"}
];
let maxResults = 3;
let resultsCount = 0;
console.log(`Code Subtle database query with limit: ${maxResults}`);
for (let record of databaseRecords) {
resultsCount++;
console.log(`Code Subtle retrieved: ${record.name} (ID: ${record.id})`);
if (resultsCount >= maxResults) {
console.log(`Code Subtle reached maximum results limit (${maxResults})`);
break;
}
}
/* Output:
Code Subtle database query with limit: 3
Code Subtle retrieved: Record 1 (ID: 1)
Code Subtle retrieved: Record 2 (ID: 2)
Code Subtle retrieved: Record 3 (ID: 3)
Code Subtle reached maximum results limit (3)
*/
Tips & Tricks:
Use break to optimize loops by exiting early once a goal condition is met
In nested loops, break only exits the innermost loop; use labeled breaks for outer loops
Consider using functions with return statements instead of break for complex logic
2.2 continue Statement
The continue statement skips the current iteration of a loop and proceeds to the next iteration. It allows you to bypass specific iterations that match certain conditions while continuing with the loop's execution.
Where to use in real life:
Filtering data during processing
Skipping invalid entries in a dataset
Implementing pagination or batched operations
Syntax:
continue;
Examples:
// Example 1: Filtering odd numbers
console.log("Code Subtle demonstrating even number filter:");
for (let i = 1; i <= 10; i++) {
if (i % 2 !== 0) {
console.log(`Code Subtle skipping odd number: ${i}`);
continue;
}
console.log(`Code Subtle processing even number: ${i}`);
}
/* Output:
Code Subtle demonstrating even number filter:
Code Subtle skipping odd number: 1
Code Subtle processing even number: 2
Code Subtle skipping odd number: 3
Code Subtle processing even number: 4
Code Subtle skipping odd number: 5
Code Subtle processing even number: 6
Code Subtle skipping odd number: 7
Code Subtle processing even number: 8
Code Subtle skipping odd number: 9
Code Subtle processing even number: 10
*/
// Example 2: Processing valid data entries
let dataEntries = [
{id: 1, valid: true, value: "First entry"},
{id: 2, valid: false, value: "Corrupt data"},
{id: 3, valid: true, value: "Third entry"},
{id: 4, valid: false, value: "Missing fields"},
{id: 5, valid: true, value: "Fifth entry"}
];
console.log("Code Subtle starting data processing");
for (let entry of dataEntries) {
if (!entry.valid) {
console.log(`Code Subtle skipping invalid entry #${entry.id}: "${entry.value}"`);
continue;
}
console.log(`Code Subtle processing valid entry #${entry.id}: "${entry.value}"`);
}
/* Output:
Code Subtle starting data processing
Code Subtle processing valid entry #1: "First entry"
Code Subtle skipping invalid entry #2: "Corrupt data"
Code Subtle processing valid entry #3: "Third entry"
Code Subtle skipping invalid entry #4: "Missing fields"
Code Subtle processing valid entry #5: "Fifth entry"
*/
// Example 3: Email validation simulation
let emails = ["user@example.com", "invalid-email", "another@domain.org", "", "test@test.com"];
console.log("Code Subtle email validation:");
for (let i = 0; i < emails.length; i++) {
let email = emails[i];
if (!email.includes('@') || !email.includes('.')) {
console.log(`Code Subtle validation failed for email ${i+1}: "${email}"`);
continue;
}
console.log(`Code Subtle sent confirmation to email ${i+1}: "${email}"`);
}
/* Output:
Code Subtle email validation:
Code Subtle sent confirmation to email 1: "user@example.com"
Code Subtle validation failed for email 2: "invalid-email"
Code Subtle sent confirmation to email 3: "another@domain.org"
Code Subtle validation failed for email 4: ""
Code Subtle sent confirmation to email 5: "test@test.com"
*/
Tips & Tricks:
Use continue to make your code more readable by avoiding deeply nested if statements
In performance-critical code, consider restructuring to avoid continue when possible
Remember that in nested loops, continue only affects the innermost loop
Subscribe to my newsletter
Read articles from Code Subtle directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Code Subtle
Code Subtle
At Code Subtle, we empower aspiring web developers through personalized mentorship and engaging learning resources. Our community bridges the gap between theory and practice, guiding students from basics to advanced concepts. We offer expert mentorship and write interactive, user-friendly articles on all aspects of web development. Join us to learn, grow, and build your future in tech!