Loops Flashcards
for loop
for (initialization; condition; increment/decrement) { }
for (let i = 0; i < 5; i++) {
console.log(i); // Output: 0, 1, 2, 3, 4
}
The for loop is used when you know the number of iterations in advance.
while loop
while (condition) {}
let i = 0;
while (i < 5) {
console.log(i); // Output: 0, 1, 2, 3, 4
i++;
}
The while loop is used when you want to repeat a block of code as long as a condition is true.
for…of loop
for (variable of iteranle) {
code
}
let arr = [10, 20, 30];
for (let value of arr) {
console.log(value); // Output: 10, 20, 30
}
The for…of loop is used to iterate over iterable objects like arrays, strings, maps, sets, etc. It returns the values of the iterable.
forEach loop
array.forEach(function(element, index, array) {
code
});
var fruits = [“banana”, “orange”, “pineapple”]
fruits.forEach(function (item, index, arr) {
console.log(“i am item”, item)
console.log(“i am the index”, index)
console.log(‘Array arr’, arr)
})
// i am item banana
// i am the index 0
// Array arr (3) [‘banana’, ‘orange’, ‘pineapple’]
// i am item orange
// i am the index 1
// Array arr (3) [‘banana’, ‘orange’, ‘pineapple’]
// i am item pineapple
// i am the index 2
// Array arr (3) [‘banana’, ‘orange’, ‘pineapple’]
can’t be stopped
we can’t return from it
argument names work by order not by name