How can I refactor this JS?

Hi friends,
I have written this js but I want to know if I can make it better.

const boxesBG = document.querySelectorAll('.boxes__content--front');

boxesBG[1].style.backgroundColor = "#38b6ff";
boxesBG[3].style.backgroundColor = "#38b6ff";
boxesBG[5].style.backgroundColor = "#38b6ff";
boxesBG[7].style.backgroundColor = "#38b6ff";

I tried this:

[1, 3, 5, 7].array.forEach(element => {
    boxesBG.style.backgroundColor = "#38b6ff";
});

console.log(boxesBG);

But it only worked on the first two.

I don’t want to have 4 lines that do the same thing. Should I create a new function?

Cheers!!!

Why not use a for loop that start at 1 and does i += 2 after each iteration?

1 Like

Hey there…

Yes it did work, that is an amazing solution… but what about accessing with an array ? and a forEach loop.

What do you mean accessing with an array? arr[i] ??

You can do it with forEach as well, although the code won’t be as clean and frankly it’s not a good fit in this situation. forEach callback function executes for every element in an array, you can use an optional index parameter and an if statement to avoid changing certain elements of an array - in your situation the elements the indices of which are even.

More on forEach here

just like the second code @john1mention with the forEach loop , you also mentioned that it can be possible and yes might not fit the situation, will be good seeying an example on it. as far as another refactor its this line of code as you mention before

for( var i = 0; i < boxesBG.length; i+=2 ){
var myBox = boxesBG[i];
 myBox.style.backgroundColor = "#38b6ff"; 
}

You don’t need myBox. ‘i’ should start with 1, not 0… since you want 1, 3, 5… Use let instead of var. But yes, you are on the right track.

not a bad idea, I will give that a shot, I just wanted to know how I could access each in the array

Ok i see. If you need to access EACH element of an array then forEach is a great choice! Honestly it would not hurt to solve this task twice - using forEach and for, just for the added practice to make sure you understand them well :wink:

For loops and looping over an array with forEach are key concepts that you’ll be using all the time, you’ll want to feel confident when using them :wink: And that only comes with practice. Good luck!

1 Like