If you missed the introductory post, it's here. For a list of previously solved katas, please refer to the bottom of this page.
If this is your first time seeing my post, please note - these katas are probably randomly assigned per user so please don't go into Codewars thinking we will have exactly the same user experience, I am just posting these in the order that I got them.
Kata #2
DESCRIPTION:
We need a function that can transform a number (integer) into a string.
What ways of achieving this do you know?
Examples (input --> output):
123 --> "123"
999 --> "999"
-100 --> "-100"
Starting code:
function numberToString(num) {
// Return a string of the number here!
}
My attempt:
function numberToString(num) {
return String(num)
// Return a string of the number here!
}
It worked! *feelsgoodman.jpg*
Although the highest voted 'Best Practice' was this with 1004 votes at the time of writing:
function numberToString(num) {
return num.toString();
}
And my approach was at rank #2 with 249 votes at the time of writing. *notbad.jpg*
Notable mention #1:
function numberToString(num) {
return ''+num;
}
Which is ranked #3 'Best Practice' with 89 votes at the time of writing but earned 633 votes for 'Clever', even higher than the ranked #1 'Best Practice' with only 156 votes. To understand why it was clever, it's because those who posted this as their solution made use of JavaScript's intricacy of converting the result into string when a number variable and string variable are (usually mistakenly) added together.
Notable mention #2:
const numberToString = num => `${num}`;
Ranked #4 'Best Practice' with only 66 votes at the time of writing but earned 267 'Clever' votes, also higher than Ranks #1 and #2 'Best Practice'. It's because users who posted this solution made use of template literals, recommended reading for which is here.
That's it for Kata #2, stay tuned for more katas to be solved!