Return Number in Words Using JavaScript

One of the answers I’ve submitted on CodeWars that gets a lot of comments is in response to this prompt:

When provided with a number between 0-9, return it in words.

Input :: 1

Output :: “One”.

If your language supports it, try using a switch statement.

The solution I’ve posted (which is very similar to the solution others have posted) is as follows:

switchItUp=n=>["Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"][n]

Since Arrays are indexed starting at zero and we can access any item in the array by its index, the way this works is by putting the equivalent word at each index, i.e.:

0 => Zero

1 => One

2 => Two

3 => Three

4 => Four

5 => Five

And the beauty of JavaScript is that we can pass a number to the switchItUp arrow function via the n parameter and it will pull out the equivalent item from the array at index n!

To break this out further, we can put this into a regular function:

function switchItUp (n) {
    const numbersAsWords = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten'];
    return numbersAsWords[n];
}

So if we pass in 5, for example, we look up index 5 in the array, which happens to correspond to ‘Five‘ and so the function returns the string.

Of course, the variable is useless since it’s only used one time, so we can remove it:

function switchItUp (n) {
    return ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten'][n];
}

And this, besides not being an arrow function for the sake of brevity, is exactly the function above.

If I were going to bring something like this into everyday use, I’d add a Number.isInteger(n) check and I’d probably make sure the array contains the index being passed so there’s no question that we’ll get the number we want.

Leave a Comment