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 Convert Strings to Numbers

Elfar Oliver
Elfar Oliver
3,924 Points

I used an entirely different method and got it to work

Instead of using: const totalBadges = parseInt(HTMLBadges) + parseInt(CSSBadges);

Which I get is the point of the lesson, but I used: console.log(${HTMLBadges} + ${CSSBadges}); and the math worked

Can anyone explain or should I not be worried and this is something I can use henceforth?

1 Answer

Steven Parker
Steven Parker
231,236 Points

That should not have worked, since you're still dealing with strings. Here, with some other examples:

// if you answer the questions with "5" and then "12":
const totalBadges = parseInt(HTMLBadges) + parseInt(CSSBadges);
console.log(totalBadges );                    // result: 17     (correct)
console.log(`${HTMLBadges} + ${CSSBadges}`);  // result: 5 + 12 (string formatting)
console.log(`${HTMLBadges + CSSBadges}`);     // result: 512    (concatenation)
console.log(HTMLBadges + CSSBadges);          // result: 512    (also concatenation)

Also, it would not have stored the result anywhere. By adding them and assigning the result to totalBadges, the original code makes it possible to add more code later to do something else with the result.