Javascript For Loops

In Javascript there are three FOR type iteration statements. The classic For loop (such as in languages like C or python). The For-Of loop which iterates through each element of an array. The For-In loop which iterates through each key in an object.

Classic For Loop

%MINIFYHTML36de96ef8596b3042afe0eb38f31fe6b23%for(let i=0; i < 10; i++){
   console.log(number * i)
} Code language: JavaScript (javascript)

In the case above, the value for number, is multiple by each iterator (i). Iterations will start at a value of 0 (i = 0), and will increase to 9. The 11th iteration (10) will be the end, and not executed. i++ signifies increasing the value of i by 1 each time.

For-Of Loop (Arrays)

for(const i of array){
    console.log(i)
}Code language: JavaScript (javascript)

Where i is the index of the array, each is printed out to the console.log in the example above

For-In Loop (Objects)

for(let k in object){
    console.log('key: ' + k)
    console.log('val: ' + object[k])
}Code language: JavaScript (javascript)

In the above statement, the loop returns all keys (k), and then outputs the value for each k (object[k])

About Author /

Leave a Comment

Your email address will not be published.

Start typing and press Enter to search