0

So, in writing a program - in javascript - that sums numbers from 1 to N (number given by user), I have written a working program, but I am still confused as to why one proposed solution that I wrote works, and the other doesn't.

This version works:

function spitback(){
var theNum = prompt("Give me a number");
var onwards = 0;
for(i = 0; i <= theNum; i++){
onwards += i;
}
  console.log(onwards);
}
spitback();

This one does not:

function spitback(){
var theNum = prompt("Give me a number");
var onwards = theNum;
for(i = 0; i <= theNum; i++){
onwards += i;
}
  console.log(onwards);
}
spitback();

Why doesn't the second one work? If I initially set var onwards as theNum (inputted by a user) and then have the function add onwards to the iterations of 'i' up until the counter reaches theNum, I will see a concatenation between theNum and all the iterations of i next to it, like it is a string. In my mind, setting a variable to the same value and then having that value change to add the counter's iteration should work! Why doesn't it work? Please share.

jb07
  • 81
  • 1
  • 9
  • Not my area of confusion. My confusion is around why setting the var onwards to theNum doesn't work and why setting onwards to 0 gets it to work. – jb07 Nov 24 '15 at 20:06

1 Answers1

3

This is because prompt returns a string, not a number. And when you use "+" operation on a string, you get concatenation, not integer increment. Javascript will not magically convert your string into integer even if it looks like it.

Vladislav Rastrusny
  • 29,378
  • 23
  • 95
  • 156
  • The first one, which uses prompt works just fine though. My confusion is around why setting the var onwards to theNum doesn't work and why setting onwards to 0 gets it to work. – jb07 Nov 24 '15 at 20:06
  • Wait, nevermind. I see the logic. Thanks Vladislav. – jb07 Nov 24 '15 at 21:39