-1

I have a function that reverses a string. I would like the function to return "Null" when a number is entered however when i input a number my function stops working. Is there something i am missing?

function reverseWords(words) {
    let eachLetter = words.split("");

    let reverseLetter = eachLetter.reverse();

    let combineLetter = reverseLetter.join("");

    if (typeof words !== "string") {
        return null;
    } else {
        return combineLetter;
    }
}

console.log(reverseWords(89));
  • function reverseWords(words) { – dahboooyyyyyyy Jun 18 '22 at 11:06
  • The problem is that `number` variables don't have a `.split(..)` function. To fix that, you can add the `typeof words !== "string"` check at the start of the function and return `null` before calling any `string` specific functions on the attribute. – Titus Jun 18 '22 at 11:08
  • Does this answer your question? [JavaScript Number Split into individual digits](https://stackoverflow.com/questions/7784620/javascript-number-split-into-individual-digits) – pilchard Jun 18 '22 at 11:08

2 Answers2

1

the operations you try to perform before the if are not possible with numbers.

Put validation as the first thing your function does and everything will work.

0

function reverseWords(words) {

if (typeof words !== "string") {
    return null;
} else {
        
   //Split the string 
  let eachLetter = words.split("");

  let reverseLetter = eachLetter.reverse();

  let combineLetter = reverseLetter.join("");


    return combineLetter;
}

}

console.log(reverseWords('89'));

You cannot apply 'split' method on numbers. First, check for the numeric value and perform the split function only when it is a string.

cnt
  • 11
  • 1