Loops & Iteration in JavaScript (Advanced)

Pranay SanjulePranay Sanjule
6 min read

Note: Try to code by yourself and understand the output

Introduction

  • In computer programming, a loop is a sequence of instructions that repeats until a specific condition is met.

  • Loops are a fundamental and powerful programming concept.

There are many ways to iterate in JavaScript i.e.

Basic Loops

  • for loop

  • while loop

  • do...while loop


  1. For Loop

  • for loops are the most common way to iterate in JavaScript.

  • They allow you to execute a block of code a specific number of times.

  • JavaScript for loop is similar to other programming languages like Java and C/C++.

Example -

// 1. for loop
// syntax :
// for (var index = 0; index < arr.length; index++){
//     condition
// }

//Example 1
for (let index = 0; index <= 5; index++) {
    // console.log(index);
}

//Example 2
let arr = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20];
// Note : Always remember in array indexing start from 0 only i.e i=0 till i<arr.length
for (let i = 0; i < arr.length; i++){
        // console.log(arr[i]);

}

//Example 3
// nested for loop
for (let i = 1; i <= 5; i++) {
    // console.log(`Outer Loop Element i ${i}`);
    for (let j = 5; j > 0; j--){
        // Note : Here i is accessible inside inner loop because of block scope
        // console.log(`Inner Loop Element j value ${j} and Inner Loop Element i value ${i}`);
    }
}

// <================#############================>

// Example 4
// Character Array
let names = ["Sita", "Ram", "Lakshman", "Hanuman"];
console.log(names.length);
for (let i = 0; i < names.length; i++){
    console.log(names[i]);
}

// Keyword => 'break' & 'continue'
// break => To break the loop
console.log(`Break Example`);
for (let i = 1; i <= 10; i++){
    if (i == 6) {
        break;
    }
    console.log(i);
}

console.log(`Continue Example`);
// continue => To skip current iteration
for (let j = 1; j <= 10; j++) {
    if (j % 2 == 0) {   //if number is divisble by 2 then skip that iteration
        continue;   
    }
    console.log(j);
}

// <================#############================>

  1. While Loop

  • while loops are similar to for loops, but they can continue iterating until a condition is met.

Example -

// 2. while loop
//Syntax:
//while(condition){

// }

//Example 1
let i = 5;
while (i>0) {
    // console.log(i);
    i--;
}

//Example 2
let count = 0;

while (count < 5) {
  console.log(`Count: ${count}`);
  count++;
}

// <================#############================>

  1. Do...While Loop

  • do...while loops are similar to while loops, but they will always iterate at least once.

Example -

// 3. do-while loop (first print then check condition)
//Syntax:
// do {

// } while (condition);

//Example 1
let j = 5;
do {
    console.log(j);
    j--;
} while (j>0);

//Example 2
let count = 0;

do {
  console.log(`Count: ${count}`);
  count++;
} while (count < 5);

// <================#############================>

High Order Array Loops

  • for...of loop

  • for...in loop

  • forEach loop

  1. For...Of Loop

  • The for...of loop is used to iterate over the values of an iterable object, such as an array, string, map, set, etc.

  • for...of loop does not work on normal objects.

Example -

// High Order Array Loops

// for...of loop
// Syntax:
// for (const iterator of object) {

// }

// Example 1
const arr = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20];
for (const i of arr) {
    // console.log(i);
}


// Example 2
const string = "Hii, I am Pranay";
for (const char of string) {
    // console.log(char);
}

// Example 3
// How to iterate normal object using for-of loop
const obj = {
    name: 'John Doe',
    age: 22,
    gender: 'male',
};

// for (const key of obj) {
//     console.log(key);    // output : Error
// }

//Note : for-in is used to iterate normal object.

// <================#############================>
  1. For...In Loop

  • The for...in loop is used to iterate over the enumerable properties of an object.

  • for...in loop iterate normal objects as well.

Example -

// for...in loop
// Syntax:
// for (const key in object) {

// }

// Example 1
const obj1 = {
    name: 'Steve',
    age: 25,
    gender: 'male',
};

for (const key in obj1) {
    // console.log(key);   // output : print key only
}

// To print value
for (const key in obj1) {
    // console.log(`${key} :- ${obj1[key]}`);  // output=> name :- Steve
}

//print array using for-in loop
const superheros = ["Ironman", "Superman", "Batman", "Spiderman"];

//Note : In js, array is also a object so it has keys which started from 0

for (const key in superheros) {
    // console.log(`${key} :- ${superheros[key]}`);
}

// <================#############================>

// Example 3
// How to iterate normal object using for-in loop
const obj = {
    name: 'John Doe',
    age: 22,
    gender: 'male',
};

// Que: Print object value
for (const key in obj) {
    console.log(obj[key]);    // output: all values of object
 }

for (const key in obj){
    console.log(`${key} :- ${obj[key]}`);    // output: key : value
}

// <================#############================>

Advanced Concept

  1. ForEach Loop

  • In JavaScript, the forEach loop is a method available for arrays, and it allows you to iterate over each element of the array and perform a specified action for each element.

Example -

// forEach Loop
// Syntax:
// array.forEach(function () {

// });

// Rules:
// 1. forEach loop takes callback function to access the array element.
// 2. function pass as a parameter .
// 3. callback function means anonymous function (function without name)
// 4. forEach loop callback function accepts 3 arguments (currentVal, index, arr)
// 5. forEach does not return value.

const realheros = ["Chatrapati Shivaji Maharaj", "Maharana Pratap", "Prithviraj Chauhan", "Ashoka the Great", "Rani Lakshmi bai"];

// 1st way
function names(realheros) {
    // console.log(realheros);
}

realheros.forEach(names);   // function reference pass as a parameter

// <=====####=====>

// 2nd way 
realheros.forEach(names => {
    // console.log(names);
});

// <=====####=====>

// 3rd way
realheros.forEach(function (names) {
    // console.log(names);
})

// <=====####=====>

// 4th way
realheros.forEach(names => {
    // console.log(names);
})

// <=====####=====>

// 5th way => Using Arrow function
realheros.forEach((names) => {
    // console.log(names);
})

// <=====####=====>

// #IMP
// forEach loop takes 3 arguments
// 1. currentVal
// 2. index
// 3. complete array

// Example
realheros.forEach((value, index, arr ) => {
    // console.log(value, index, arr);
})

// Iteration over array of objects (Common concept in JS)

const founder = [
    {
        name: "Elon Musk",
        company: "Tesla"
    },
    {
        name: "Steve Jobs",
        company: "Apple"
    },
    {
        name: "Jeff Bezos",
        company: "Amazon"
    },
    {
        name: "Mark Zuckerberg",
        company: "Facebook"
    }
]

founder.forEach((item) => {
    console.log(`${item.company} :- ${item.name}`);
})

// <================#############================>

  1. Map() Object in JS

  • In JavaScript, the Map object is a collection of key-value pairs where each key and value can be of any data type.

  • It allows you to store, retrieve, and manipulate data in a more flexible way than a simple JavaScript object.

  • Map object is iterated by a key-value pair.

  • All collections in map are unique.

  • Map object has many methods such as set, get, delete, forEach, values, clear, entries, has, keys, etc.

// Map() Object
const myMap = new Map();

myMap.set('user1', 'John');
myMap.set('user2', 'Steve');

// Que: Print key of map only
for (const key of map) {    // won't work
   // console.log(key);    // output: complete array will print
}

for (const [key, value] of map) {
    console.log(key);    //output: only key will print
}

// <================#############================>

💡
RESOURCES

0
Subscribe to my newsletter

Read articles from Pranay Sanjule directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Pranay Sanjule
Pranay Sanjule

Learner, Tech-Enthusiast