Javascript ‘for’ Loops

Categories coding, javascript, loops

// Print the numbers 1 through 10

for (i=1;i<=10;i++) {

// Output: 


Suppose you have an array called ‘cars’ that has a long list of cars like corvette, mustang, tahoe, etc.. You want to create a string that lists out all the cars you have.

you *could* do it this way:

let carSentence = 'These are the cars I have:';

carSentence += 'a ' + cars[0] + ', ';

carSentence += 'a ' + cars[1] + ',';

carSentence += 'a ' + cars[2] + ',';

and so on… to create the string you want to make.


or, you could use a snazzy for loop

let cars = ['corvette','tahoe','mustang','corolla','jeep']

carSentence = 'These are the cars I have: ';

for(i=0;i<cars.length;i++) {
    carSentence += 'a ' + cars[i] + ', ';

carSentence += 'and others.'


These are the cars I have: a corvette, a tahoe, a mustang, a corolla, a jeep, and others.


for loop takes three parameters: 1) declaring a counter variable,  (i=0) 2) specifying a condition which, when false, ends the loop (i < 100), and 3) specifying the action performed upon the counting variable (i++). The main block of the function (inside the curly braces after the three parameters are specified) specifies what the function needs to do each time it runs, much like any function.

Often, one will use the counter variable (in this case ‘i’) to iterate through an array by aligning ‘i’ with the index number of the variable and accessing each successive variable value as the counter variable is incremented by one, per the example given here.

for further reading, check out mozilla developer’s documentation.


Leave a Reply

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