Home > database >  Function does not work when entering number javascript
Function does not work when entering number javascript

Time:06-19

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));

CodePudding user response:

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.

CodePudding user response:

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.

  • Related