Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Numbers Working with Numbers Treating Strings As Numbers

James Pang
James Pang
2,945 Points

How does the Javascript produce the number 105 when adding together two strings?

I understand that the JavaScript engine interprets the two variables as strings. I am just curious as to why adding the two strings together produces the specific number of 105. And how does it relate to concatenation?

4 Answers

So remember concatenation with Strings is (certainly in this context) jamming two strings together, regardless of whether it makes any logical sense.

With with this program asking about badges, the responses (the strings) are taken, and just put next to each other in a new string. So '10' and '5' just become '105'. This string (stored as totalBadges) is then fed out through the console.log line. '8' and '6' would become '86', and so on. There's no mathematical operation or logic going on here other than pushing two strings together.

To prove it, type words as the responses- 'banana' and 'marshmellow' become 'bananamarshmellow' in the console.

Following along with the instructor, he submits an input of 10 for HTML badges and an input of 5 for the CSS badges. As you know, since they're initially recognized as strings, these two inputs are simply put side by side next to each other, which produces 105. If the parseInt() method had been used for the input submitted for the HTMLBadges and CSSBadges, then the value for both would have been recognized as numeric values. Thus producing a value of 15 instead.

I hope that made sense.

Basically it just put anything together without logical sense. 00 + 00 = 0000

Because the number that the user entered was treated as the string. So example if the user first entered was 10, and the second entered was 5. Because it was treated as the string, so they are concatenate the two string, so it becomes 105 as the string, not an integer.