Iteration in javascript:
- Iteration in JavaScript refers to repeatedly executing a block of code over a sequence of values, such as arrays, objects, or other iterable structures.
- JavaScript offers multiple loop constructs, array iteration methods, and iterator protocols to handle different scenarios efficiently.
Array Iteration Methods:
- Array iteration methods operate on every array item.
- In JavaScript, array iteration methods are built-in functions that allow you to loop through (iterate over) each element of an array and perform some operation on them without manually writing a for loop.
- These methods make code shorter, cleaner, and more readable.
1. The for...of Loop:
The for...of statements hands you the array values.
Example:
const cars =["bmw","volvo","mini"];
for (let car of cars){
console.log(car);
}
output:
bmw
volvo
mini
2. The for...in Loop:
The for...in statements hands you the array indexes.
Example:
const cars =["bmw","volvo","mini"];
for (let car in cars){
console.log(car)
}
output:
0
1
2
3. JavaScript Array forEach():
The forEach() method calls a function (a callback function) for each array element.
the function takes 3 arguments:
- The item value
- The item index
- The array itself
Example:
const numbers = [45,4,9,12,15];
numbers.forEach(display);
function display(value,index,array){
console.log(value, index, array)
}
output:
45 0 (5) [45, 4, 9, 12, 15]
4 1 (5) [45, 4, 9, 12, 15]
9 2 (5) [45, 4, 9, 12, 15]
12 3 (5) [45, 4, 9, 12, 15]
15 4 (5) [45, 4, 9, 12, 15]
Callback function:
A callback function in JavaScript is a function that is passed as an argument to another function and is executed later, usually after some operation has completed or when an event occurs.
Callbacks are commonly used for:
- Asynchronous operations (e.g., reading files, making API calls)
- Event handling (e.g., button clicks)
- Customizable function behavior
Types of callbacks:
Synchronous Callbacks:
- Executed immediately during the execution of the function they are passed to.
- Commonly used in array methods like .map(), .filter(), .forEach().
example:
function greet(callback) {
console.log("Hello ");
callback();
}
function sayBye() {
console.log("Goodbye!");
}
greet(sayBye);
output:
Hello
Goodbye!
Asynchronous Callbacks:
- Executed later, often after an operation completes (e.g., timers, API calls, file reading).
- Common in event handling and I/O operations.
4. JavaScript Array map():
- The map() method creates a new array by performing a function on each array element.
- The map() method does not execute the function for array elements without values.
- The map() method does not change the original array.
example:
const num = [45, 4, 9, 12, 15];
num.map(display);
function display(value, index, array) {
console.log(value, index, array)
}
console.log(num);
output:
45 0 Array(5)
4 1 Array(5)
9 2 Array(5)
12 3 Array(5)
15 4 Array(5)
Differences between forEach() and map() methods:
Reference:

Top comments (0)