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 trialRyan Smith
1,936 PointsWhy 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
19,198 Pointswhen 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
Front End Web Development Techdegree Student 3,900 PointsI 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 don
t wanna see as a just string like "57", you would have to put into parentheses (input_5 + input_7) = 12