Day 8: JavaScript — ‘For Loops’

If You Don’t Want To Repeat

To continue from the other day’s comment on D.R.Y (Don’t Repeat Yourself), it seems that this coding has a lot to do with efficiency. The ‘for’ loop seems to be a great function for allowing programmers to repeat steps without having to manually write the same code multiple times. ‘For’ loops require a ‘counting variable’, ‘loop controller’ and an increment/ decrement element. The below code is an example of a loop that counts & prints from 5 to 50 by increments of 5…


for (var i = 5; i < 51; i +=5) { //runs for loop starting at 5 up to <51, by 5

| console.log (i); //counts and prints out 5,10,15,20,…50 to the console

} // end of the loop


step 1: Declare variable ‘i’ as counting variable

step 2: Define controlling condition for loop. Be careful to not make an infinite loop, as I continually read that it will crash your browser/ computer. I feel this is something that I do not need to test to confirm.

step 3: Define the increment/ decrement of the counting variable.

step 4: Print the count to the console

step 5: End the loop

Arrays — When one element isn’t Enough

At the beginning most of the variables we use have one value assigned to them. However, there are times where we may want to have lists or different data types stored in a variable. Enter…Wonderful Arrays.


var cities = [“Washington”, “Seattle”, “Portland”, “Boise”]; //defines array variable

console.log ([1]);


step 1: Define the Array variable -> e.g. cities

step 2: Assign elements to the Array -> “Washington”, “Seattle”, “Portland”, “Boise” (Remember to use quotes when working with string text)

step 3: Print out the element 1 to the console. Results = “Seattle”…What that doesn’t make sense. I went to elementary school and “Washington” should be 1. If we were not working with arrays possibly; however, arrays index from a starting point of ‘0’.

Put It All Together -> Loops and Arrays

Say you wanted to send a list of things you want to eat to group of vendors. I may be tiring to repeat the same list to every vendor. Why not just create a ‘For’ loop and push REPEAT…


var food = [“Hamburgers”, “Hotdogs”, “Fish”, “Green Beans”]

var myName = “Johnny Quest”;

for (var i = 0; i < food.length; i ++) {

| console.log (“Hi, I am” + “ “ + myName + “ “ + “and I would like to order” + “ “ + food[i] + “ please.”);


Next on the schedule is While loops.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.