Skip to content
Advertisement

Taking numbers from a const array and adding +2 to each number | Must Use for Loop

    const addTwo = [1, 2, 3, 4, 5];
    
    for (let i = addTwo.length; i >= 5; i++) { 
      addTwo = addTwo += 2 //I know this does not work
  
      
    }
    
  console.log(addTwo); // -> should print [3, 4, 5, 6, 7];

Hi there,

New to js and working on using an array with a for loop. In this problem it’s asking me to specifically use a for loop to get a solution. I was able to get my answer using splice. But, to be honest I thought this was a little heavy handed and lazy to me. I didn’t think it was going to help me learn anything. I have exhausted many options online. Looking at various videos on the subject of for loops.

I just felt I could use some help from the pros. I get a “Type Error on line 4: Assignment to constant variable.” Now, as I understand you can’t change a constant variable. Any ideas what I could use as a beginner? Thank you for your patience and help!

Advertisement

Answer

You need to assign to the array element, not the whole array. And the indexes in the loop are wrong. You should start from 0 and go up to the length-1. Your loop will repeat infinitely because i >= 5 is always true when you start with i = 5 and keep adding 1 to it.

const addTwo = [1, 2, 3, 4, 5];

for (let i = 0; i < addTwo.length; i++) {
  addTwo[i] += 2;
}

console.log(addTwo);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement