When I do a sum of numbers, it returns them together, as if they were text strings, does anyone know what I'm doing wrong? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

When I do a sum of numbers, it returns them together, as if they were text strings, does anyone know what I'm doing wrong?

//Creating the class class Persons { constructor(name, age, email, city, working){ this.name = name; this.age = age; this.email = email; this.city = city; this.working = working; } //Method to see the characteristics of the user show() { console.log("Name: " + this.name); console.log("Age: " + this.age); console.log("Email: " + this.email); console.log("City: " + this.city); console.log("Working: " + this.working); } } //Saving objects in variables const person1 = new Persons("Max", 24, "example@gmail.com", "Washington", true); const person2 = new Persons("Matt", 21, "example@gmail.com", "Portland", true); console.log(person1.show()); console.log(" "); console.log(person2.show()); //To see the sum of ages function sumAge(age) { let agePeople = { age1: person1.age, age2: person2.age }; console.log("The sum of ages is: " + agePeople.age1 + agePeople.age2); } sumAge();

1st May 2021, 2:53 AM
Josenmta
Josenmta - avatar
6 Answers
+ 3
Yes, just like in my example. Put the numeric calculation in parentheses. console.log("The sum of ages is: " + (agePeople.age1 + agePeople.age2));
1st May 2021, 3:50 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
When you concatenate a string to a number the number is implicitly converted to a string. "Nums: " + 4 + 2 This concatenates from left to right, so that 4 is first converted to a string effectively changing it to; "Nums: 4" + 2 Then it is repeated for the next number so the result is; "Nums: 42" In or to give the calculation higher precedence you can put it in parentheses like; "Nums: " + (4 + 2) Now the calculation will occur then the concatenation. "Nums: " + 6 Then to; "Nums: 6"
1st May 2021, 3:32 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
Thanks friend, it served me just as you said, you clarified this part for me that I had no idea how to fix.
1st May 2021, 3:54 AM
Josenmta
Josenmta - avatar
0
Thanks Chaotic Dawg, would you know how to implement this solution in the code?, If you can.
1st May 2021, 3:43 AM
Josenmta
Josenmta - avatar
0
You could also use a comma to separate them for the console.log output like; conaole.log("The sum of ages is:", agePeople.age1 + agePeople.age2); Note: a space will be inserted between each argument when output.
1st May 2021, 3:54 AM
ChaoticDawg
ChaoticDawg - avatar
0
All Right
1st May 2021, 3:57 AM
Josenmta
Josenmta - avatar