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!

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 The Solution

Ryan Smith
Ryan Smith
1,936 Points

Why are the parentheses needed in this line of code?

I feel stupid asking, but can someone explain why the parentheses are needed here to enforce addition instead of concatenation? Since after using parseFloat the two input variables become floats instead of strings, and they aren't otherwise turned into strings that I can understand?

message += input1 + " + " + input2 + " = " + (input1 + input2);

Thank you!

2 Answers

turaboy holmirzaev
turaboy holmirzaev
18,412 Points

when you add String to a Number, javascript converts the number into a string and concatenate them. for example: "5" + 10 => would be "510" (even though 10 is a integer, it gets converted to string when the first operand is string) but in this case: 5 + 10 = 15 => because both are integers. or another example is: "I am " + 5 + 7 => would be a string "I am 57" why: First operation here is: adding "I am " to 5 which will result in "I am 5" (5 becomes string) Second operation is: adding "I am 5" to 7 which will result in "I am 57" (7 becomes string) or: "I am " + (5 + 7) First operation would be to evaluate inside parenthesis( math precedence () * / + - order) which would 12(integer) Second operation would be to add "I am " + 12 which will produce "I am 12"(12 becomes string)

Lucas Guimarães
Lucas Guimarães
Front End Web Development Techdegree Student 3,900 Points

I think its because that is an operation, so that is why you need to tell the JavaScript to some those value instead of leaving them as a string. In other words, if you dont wanna see as a just string like "57", you would have to put into parentheses (input_5 + input_7) = 12