1var colors=["red","blue","green"];
2for (let i = 0; i < colors.length; i++) {
3 console.log(colors[i]);
4}
1let str = "";
2
3for (let i = 0; i < 9; i++) {
4 str = str + i;
5}
6
7console.log(str);
8// expected output: "012345678"
9
1let array = ['Item 1', 'Item 2', 'Item 3'];
2
3// Here's 4 different ways
4for (let index = 0; index < array.length; index++) {
5 console.log(array[index]);
6}
7
8for (let index in array) {
9 console.log(array[index]);
10}
11
12for (let value of array) {
13 console.log(value); // Will each value in array
14}
15
16array.forEach((value, index) => {
17 console.log(index); // Will log each index
18 console.log(value); // Will log each value
19});
1JavaScript supports different kinds of loops:
2
3for - loops through a block of code a number of times
4for/in - loops through the properties of an object
5for/of - loops through the values of an iterable object
6while - loops through a block of code while a specified condition is true
7do/while - also loops through a block of code while a specified condition is true
8
9for (let i = 0; i < cars.length; i++) {
10 text += cars[i] + "<br>";
11}
12
1JavaScript For Loop: Summary
2There are three types of for loops: the regular for loop, the for/in loop and for/of loop.
3The for loop iterates through an array.
4The for/in loop iterates through the properties of an object.
5The for/of loop iterates through iterable objects, like arrays and strings.