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

for(let i=0; i < 10; i++){ console.log(number * i) }

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) }

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]) }

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

Leave a Reply

Your email address will not be published. Required fields are marked *