"I am Saqib Jahangir. A passionate vlogger, software engineer, trainer and avid traveler with a deep love for exploring the hidden gems of our beautiful planet. With a strong foundation in Application Development, Application Architecture & Database Design and Product Management, I bring over a decade of hands-on experience building secure, scalable, and resilient web applications for a diverse range of industries."

JavaScript Loops and Iterators (Advanced)

 

Beyond basic for and while loops, JavaScript provides advanced iteration methods and special loops for working with objects and arrays more efficiently.


1. for...in Loop

for...in is used to loop over the properties of an object.

let person = { name: "Alice", age: 25, city: "Dubai" };
 
for (let key in person) {
  console.log(key + ": " + person[key]);
}
// Output:
// name: Alice
// age: 25
// city: Dubai

Note: Avoid using for...in on arrays—it’s meant for objects.


2. for...of Loop

for...of is used to loop over the values of an iterable (like arrays, strings, or sets).

let colors = ["red", "green", "blue"];
 
for (let color of colors) {
  console.log(color);
}
// Output:
// red
// green
// blue

3. map() Method

map() creates a new array by applying a function to each element.

let numbers = [1, 2, 3, 4];
let squared = numbers.map(num => num * num);
 
console.log(squared); // [1, 4, 9, 16]

4. filter() Method

filter() creates a new array with elements that pass a condition.

let ages = [12, 18, 25, 30, 15];
let adults = ages.filter(age => age >= 18);
 
console.log(adults); // [18, 25, 30]

5. reduce() Method

reduce() runs a function on each element to reduce the array to a single value.

let prices = [5, 10, 15];
let total = prices.reduce((sum, price) => sum + price, 0);
 
console.log(total); // 30

 

Popular Posts

Operators (Arithmetic, Comparison, Logical)

Functions (Built-in & User-defined)