Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Challenge: While Loops - Conditional Expression

I am working through a precourse challenge and I've tried a few different things to try and get this to work. But I am at a loss as to what I am doing wrong. This is the challenge:

Initialize a variable addThis to 0 and a variable sum to 0. Use a while loop to repeat a code block as long as addThis is less than 10. In the code block, add the value of addThis to sum, then increment addThis by 1. After the while loop runs, the value of sum should be the sum of the numbers 0 through 9.

The Challenge Error: expected 0 to equal 45

And my code:

let addThis = 0;
let sum = 0;
while (addThis < 10) { 
  addThis += sum;      
  addThis++
}
// Uncomment the line below to check your work!
console.log(sum);
like image 682
ok cool Avatar asked Feb 04 '26 04:02

ok cool


1 Answers

let addThis = 0;
let sum = 0;
while (addThis < 10) { 
    sum += addThis
    addThis++
}

console.log(sum);

You made a little mistake with your adding order x += y will assign x add y to x. Not the other way around.

like image 50
destroyer22719 Avatar answered Feb 06 '26 17:02

destroyer22719



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!