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 trialLinda Hung
Courses Plus Student 1,099 PointsIs it better, or easier to read, if I use the unary plus operator to convert my variable to numbers throughout the code?
Instead of converting the strings to numbers using parseInt(), I used the unary plus operator throughout the code. Which option is better in terms of reading the code? Is it just a stylistic choice?
1 Answer
Doron Geyer
Full Stack JavaScript Techdegree Student 13,897 PointsHI Linda Hung I think either one would be fine to use from a functional stand point although the unary + operator is has different behavior to parseInt in different situations. take for example
pasrseInt('123abc') // 123
(+'123abc') //NaN
this stackoverflow will give you an in depth breakdown of the differences. https://stackoverflow.com/questions/17106681/parseint-vs-unary-plus-when-to-use-which
I think however that you should keep in mind at this point in your coding journey , the focus is a lot less on the most correct use case or ideal syntax and more on teaching you principles, like the different way your code handles numbers and strings.
another example of this is throughout the early stages you use var for variables . You will see later that it is often a lot better to use const and let for several reasons.
It's great to ask questions now , early on but focus on understanding and learning the principles rather than the methods.
If this response helped resolve your question please select best answer to mark it solved.
Happy coding!
Linda Hung
Courses Plus Student 1,099 PointsLinda Hung
Courses Plus Student 1,099 PointsThank you, Doron Geyer , for breaking it down for me, and providing a link as well! I understand now :)