0

I'm supposed to use a while loop to traverse this array and multiply each item by 2. The page just keeps loading forever when I try to run it.... What am I missing? Thank you.

var prices = [4, 5, 8, 10];

var i = 0;
while (i < prices.length){
    prices[i]++;
    i*=2;
}

console.log(prices);
  • 3
    `i` is `0` at the start of your loop, and `0` * anything is `0`. – joews Jul 07 '17 at 19:58
  • 2
    Use a debugger and think about what you need to do and what you are actually doing. Step through each iteration of that loop and pay attention to what you are doing to `i` and what `i` represents. Hint, is `i` your index or your value? – scrappedcola Jul 07 '17 at 19:59
  • read the code out load. you are saying take the value in the index of the array and increment it by one. After that you say take the increment value for the while and multiply it by two. you are NOT doubling the array like your description says. – epascarello Jul 07 '17 at 20:04

2 Answers2

5

You swapped the increments:

var prices = [4, 5, 8, 10];

var i = 0;
while (i < prices.length){
    prices[i] *= 2;
    i++;
}

console.log(prices);
Alberto Trindade Tavares
  • 10,056
  • 5
  • 38
  • 46
  • You fixed my problem? Any way you can help me understand why we format like this? – Tyler Slay Jul 07 '17 at 20:01
  • The problem was because you initialized i as 0 and multiplied by 2 at each iteration, which always result in 0, so that's why you entered in a infinite loop. Incrementing i by zero (adding 1 at each iteration) changes its value and makes the loop stops when i reaches the length of the array - 1. – Alberto Trindade Tavares Jul 07 '17 at 20:02
  • The problem really was that switch. You was multiplying i by 2 and incrementing prices[i] by 1, when you should increment i by 1 and multiply prices[i] by 2 – Alberto Trindade Tavares Jul 07 '17 at 20:03
  • 1
    To put it more bluntly. `i` starts out as zero. Is 0*2 ever going to equal the length of prices? – scrappedcola Jul 07 '17 at 20:06
-1

As others have pointed out, you have a logic error in the way you are calculating the updated prices. You are multiplying the iterator and not the price.

ES5 solution.

var prices = [4, 5, 8, 10];
var updatedPrices = prices.map(function(item) {
  return item *= 2;
});

console.log(updatedPrices);

/**
 [
  8,
  10,
  16,
  20
]
*/

ES6 solution.

const prices = [4, 5, 8, 10];
const updatedPrices = prices.map(item => item *= 2);

console.log(updatedPrices);

/**
 [
  8,
  10,
  16,
  20
]
*/
Matt
  • 5,315
  • 1
  • 30
  • 57