Loops Flashcards

1
Q

for loop

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

while loop

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

for…of loop

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

forEach loop

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly