0

I am currently learning JS and when I do some practice, I find some issues I am unclear on data type in Javascript. I understand that JS do NOT require specific type indication, it will automatically do the type conversion whenever possible. However, I suffer one problem when I do NOT do type conversion which is as follows:

 var sum = 0;
 function totalSum (a) {
 if (a == 0) {
 return sum;
 }
 else {
 sum += a;
 return totalSum(--a);
 }
 }
 var i = prompt("Give me an integer");
 // var num = parseInt(i); 
 alert("Total sum from 1 to " + i + " = " + totalSum(i));
 // alert("Total sum from 1 to " + i + " = " + totalSum(num));

I notice that the code works perfectly if I change the data type from string to int using parseInt function, just as the comment in the code does. BUT when I do NOT do the type conversion, things are getting strange, and I get a final result of 054321, if I input the prompt value as 5. AND in a similar way, input of 3, gets 0321 and so on.

Why is it the case? Can someone explain to me why the totalSum will be such a number? Isn't javascript will automatically helps me to turn it into integer, in order for it to work in the function, totalSum?

The sample code can also be viewed in http://jsfiddle.net/hphchan/66ghktd2/.

Thanks.

asked Jun 29, 2015 at 11:17
1
  • i is a string, need to convert it to a number, Number(i) Commented Jun 29, 2015 at 11:18

2 Answers 2

1

I will try to decompose what's happening in the totalSum method.

First the method totalSum is called with a string as parameter, like doing totalSum("5");

Then sum += a; (sum = 0 + "5" : sum = "05") (note that sum become a string now)

then return totalSum(--a);, --a is converting the value of a to a number and decrement it's value. so like calling return totalSum(4);

Then sum += a (sum = "05" + 4 : sum = "054") ...

answered Jun 29, 2015 at 11:31
Sign up to request clarification or add additional context in comments.

Comments

0

See the documentation of window.prompt: (emphasis mine)

result is a string containing the text entered by the user, or the value null.

answered Jun 29, 2015 at 11:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.