DEV Community

Chinwendu Agbaetuo
Chinwendu Agbaetuo

Posted on • Updated on

Creating Functions in JavaScript - Part 1

Create a function that takes a number from 0 to 5 and returns the English word for that number. For example, 1 should return "one".

const numbers = [
  ["0", "zero"],["1", "one"], ["2", "two"], ["3", "three"], ["4", "four"], ["5", "five"]
]

const stringFromNumber = (num) => {
  if (num >= 0 && num <= 5) {
    const getIndex = numbers[num];
    return console.log(getIndex[1]);
  } 

    return console.log(`The number '${num}' is out of range`); 
}

stringFromNumber(0);
stringFromNumber(1);
stringFromNumber(2);
stringFromNumber(3);
stringFromNumber(4);
stringFromNumber(5);
stringFromNumber(-1);
stringFromNumber(6);
Enter fullscreen mode Exit fullscreen mode
> "zero"
> "one"
> "two"
> "three"
> "four"
> "five"
> "The number '-1' is out of range"
> "The number '6' is out of range"
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
mike_earley_2ac31f69e25a7 profile image
Mike Earley

The If statement isn’t necessary, just put zero as the first entry in the array. That also removes the necessity of num -1, because the index will line up with the values

Collapse
 
dindustack profile image
Chinwendu Agbaetuo

Thanks for your response. I appreciate that you took the time to review the code and offer corrections.