Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Ryan McFarlane14,843 Points
Any reason why Number() was not mentioned? Seems to function almost exactly the same as unary plus + operator
Number() seems to return almost exactly the same values as the unary plus + operator but it wasn't mentioned. Is there any reason why? It's definitely more readable even though it's longer.
Oh, really interesting question, Ryan! I think the most straightforward answer to your question is that - at least in this stage of your expected / assumed learning process - the unary plus (+) operator can be explained in terms that are more meaningful or digestible than delving into the Number() constructor. To really get a grasp of how the Number() constructor works, or to explain it in an effective way, you'd need to familiarise yourself with objects (and primitive wrapper objects), and constructors. But it's not really needed at this point.
You're totally right that the Unary (+) Operator will return the same values at Number(), and that's because it's completing the same process under the hood.
This is taken from the ECMA specs for the Unary (+) Operator:
11.4.6 Unary + Operator The unary + operator converts its operand to Number type.
Basically, it's the equivalent to the Number() constructor called as a function. It achieves the same goal, but is a little easier to write and understand - and helps achieve the goal of making coding more accessible.
Steven Parker218,528 Points
parseInt() is preferred for most situations. The behaviors of the various conversion mechanisms varies a bit, it's a good idea to understand how they differ before making a choice. Here's a chart of examples for each: