1

I'm a newbie in JavaScript and I'm trying to do simple exercises everyday. Can you please explain me why, my for loop only returns the last item in my array? Thanks a lot in advance! The code is:

let button = document.querySelector ('.button');
let background = document.querySelector ('body');
let colors = ['black', 'blue', 'green', 'white', 'brown', 'yellow'];
button.addEventListener ('click', function(){
 for (let i= 0; i< colors.length; i++) {
 let index = colors [i];
 background.style.backgroundColor = index;
 }
})

P.S. I also tried it like: background.style.backgroundColor = colors[i]; (without adding index variable). Still i get only the last color, which is yellow.

asked Apr 20, 2020 at 20:27
5
  • 1
    Your loop just re-assign a new value to backgroundColor property at every iteration. What is expected: array of colors? Commented Apr 20, 2020 at 20:29
  • 1
    Well, it does change the color to black. And then blue. And then green. And finally to yellow. And all that happens in less than a millisecond, so you can't see it. Commented Apr 20, 2020 at 20:30
  • 1
    If you want to see the changes, put what is in the for loop inside the setTiemout function. All inside for loop Commented Apr 20, 2020 at 20:32
  • One nomenclature thing: Your loop does not "return" anything. Your loop iterates through the items in the colors array, and sets a property. There are no return statements in the loop (nor in the enclosing function). We are taking your question to mean, "why does the 'for' loop only set the value of the property to the last item in the array?" Commented Apr 20, 2020 at 20:33
  • even if the colors are assigned one by one, your loop rotates too fast for you to be able to see them (a few milliseconds). only the last color of your list remains visible Commented Apr 20, 2020 at 20:51

5 Answers 5

1

Why does 'for' loop only returns the last item in the array?

Because you tell it to do so. the for loop you are using inside the click listener will always run until it reaches the length of the array ( i < colours.length ), which means the latest element; I guess you instead try to change background on each click, and for is not a proper tool for that, you simply need some "index" that you increase every time it clicked, and reading the colour of that "index" from colours array;

let button = document.querySelector ('.button');
let background = document.querySelector ('body');
let colors = ['black', 'blue', 'green', 'white', 'brown', 'yellow'];
let colorIndex = 0;
button.addEventListener ('click', function(){
 background.style.backgroundColor = colors [colorIndex % colors.length];
 colorIndex++
})
<button class="button">change bg</button>

answered Apr 20, 2020 at 20:39
Sign up to request clarification or add additional context in comments.

Comments

0

From what I understand you want to change the color of the element when it is clicked to the button. Your for loop will change the background when you click but it will happen very fast that you will not be able to see. With this code, you can change the color after every click by picking the next value in the colors array. Code:

let button = document.querySelector('.button');
let background = document.querySelector('body');
let colors = ['black', 'blue', 'green', 'white', 'brown', 'yellow'];
let cIndex = 0;
button.addEventListener('click', function () {
 background.style.backgroundColor = colors[cIndex];
 if (cIndex >= colors.length - 1) {
 cIndex = 0;
 } else {
 cIndex++;
 }
});

Explanation - First we create a cIndex variable to start from the beginning of the array. Then every time we click to the button cIndex gets incremented to get the next value in the array next time we click the button. Then we check if we reached the end of array with if statement. If we reached to the end of array we equal cIndex to zero to go back to the first value in the array.

answered Apr 20, 2020 at 20:38

1 Comment

Now I understand. You're good in explaining! Thanks a lot! <3
0

You should put value of current index in closure, like this:

let button = document.querySelector ('.button');
let background = document.querySelector ('body');
let colors = ['black', 'blue', 'green', 'white', 'brown', 'yellow'];
let index = 0;
button.addEventListener ('click', function(){
 const _index = index++;
 background.style.backgroundColor = colors[_index];
 if (index === colors.length) {
 index = 0;
 }
})
answered Apr 20, 2020 at 20:39

Comments

0

When performing the cycle, first put "black" then "blue" and so on. last put "yellow". Each placed element of colors array replaces the previous one, so you last see "yellow". If you want to get random color from your array tyr this:

let button = document.querySelector ('.button');
let background = document.querySelector ('body');
let colors = ['black', 'blue', 'green', 'white', 'brown', 'yellow'];
button.addEventListener ('click', function(){
 let r = Math.floor(Math.random() * colors.length) + 0;
 background.style.backgroundColor = colors[r];
});

Read more here: https://www.w3schools.com/js/js_random.asp

answered Apr 20, 2020 at 20:52

1 Comment

Thanks a lot! <3
0

Same answer with ES7 code

const delay = ms => new Promise(res=>setTimeout(res,ms))
 , colors = ['orange', 'blue', 'green', 'pink', 'crimson', 'yellow']
 ;
document.querySelector('#button-loop').onclick = async ()=>
 {
 for (let color of colors)
 {
 document.body.style.backgroundColor = color
 await delay(1500) // slow down colors changing
 }
 }
 
let colorId = -1
document.querySelector('#button-next').onclick = () =>
 {
 colorId = ++colorId % colors.length
 document.body.style.backgroundColor = colors[colorId]
 }
<button id="button-loop">color loop</button>
<button id="button-next">color next</button>

answered Apr 20, 2020 at 22:23

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.