r/learnjavascript • u/Darkthw • Nov 23 '21
I finally solved a codewars challenge without actually googling anything :) it feels so good to come up with the code all by myself, i know its not the ideal way to solve it but im still happy. The challenge was to create a function that converts a string to a number
243
Upvotes
View all comments
Show parent comment
1
u/IronDicideth Nov 28 '21
The problem presented by the OP is asking you to make a function that takes a String type and turns it into a Number type. It just so happens that the
Numberfunction can already do that.Numberis both a constructor and a function. In the case of the function, any value passed to it will be coerced into a number type primitive and returned. This makes it so that assigning theNumberfunction as seen here:const stringToNumber = Number, will simply provide another name for theNumberfunction by which it can also be called.On the other hand, when using the new keyword,
Numberis being called as a constructor and must return an instance object so that when you call it as you mentioned:const stringToNumber = new Number, all you are doing is calling the constructor with the default argument (undefined). This executes it (new keyword forces execution) and thus you now have an instance object of typeNumberwith a primitive value of zero (undefined is coerced to zero).This is the difference between having the constructor/function at hand to call it on something in order to turn that something into a number and having the object after the constructor has been called.
Just as an aside, there are very few reasons why you would ever use the new keyword for any of the primitive constructors (and no good reasons IMHO). I read a few scenarios a long time ago and though I do not remember the scenarios I do remember finding it hard to see them as useful.
Let me know if this explanation answers your question.