Fill in the code below to reverse the list of colors, reverse each word in the list, and then print out each word, starting with 'teliov' .

const rainbow = [‘red’, ‘orange’, ‘yellow’, ‘green’, ‘blue’, ‘indigo’, ‘violet’];

for (let ri = rainbow.length - 1 ; ri >= 0; ri -= 1) {

let color = rainbow[ri];

let result = ’ ';

for (let ci = color.length-1; ci >= 0; ci -= 1 ){

result += color[ci];




I am starting to get the hang of JS loops…because of the help on this forum. I was able to figure out this exercise by filling in the blanks but not comprehending it. How does it work?? Thanks in advance for your help!

So you have a couple steps to take to do what the question asks!

  1. Reverse the list, that is, take the last element and make it the first, second last becomes second etc.
  2. Reverse each word within the list so that it is read backwards.
  3. Print out each word.

So starting from point 1, you know that a for loop can be used to cycle through every element and a list, and that to reverse you need to start from the last element. Hence we decide to write the for loop:

Here, rainbow.length would return the number of elements in the list, which in this case is 7 however JS is 0-indexed so the indexes for a list of length 7 are [0, 1, 2 , 3, 4 , 5, 6]. Hence the last element will be rainbow.length - 1, and so that is our starting variable. We want it to loop backwards through the list to index 0, hence the rest of the loop condition there.

So now we’ve started from the last element, we want to reverse that element i.e. step 2. Therefore using the same logic for the list, this time applied to characters in a string, we want to start from the last letter, and loop backwards, appending these letters to a new string. Hence your for loop condition looks like this:

and we can see this is functionally identical to the previous loop condition, just using the word instead of the list as the variable. So this loops backwards through the word and adding the letters to a new temporary string that will be our reversed word. So it’ll take the last letter and make it the first, second last becomes second etc.That’s when step 3 comes in, and you console.log() the resulting reversed word, as you want it to be first printed out since it is last in the list.

This then goes back to the initial loop, selecting the second last word and repeating this process, until you have printed out the list of words, in reverse order which each word reversed. Hopefully this makes sense, and do ask if you have any more questions!

1 Like