Error:Make sure your if/else if/else statement returns a string when the function input isn't a number


#1

var isNum = function(number) {
    var number_parsed = parseFloat( number );
    if (isNaN(number) || typeof number == 'string' ){
          return "enter the number not the string"
    } else if(number_parsed % 2 ===0){
        return true
    } else{   
        return false
    }
};
isNum('berry');

When I run this code it gives me error that if/else if/else statements should return string.


#2

Your code returns true or false, which are variables of the boolean type. They need to return strings, even in the event your else if and else branches are reached.


#3

The parseFloat() function parses a string and returns a floating point number.

This function determines if the first character in the specified string is a number. If it is, it parses the string until it reaches the end of the number, and returns the number as a number, not as a string.

Note: Only the first number in the string is returned!

Note: Leading and trailing spaces are allowed.

Note: If the first character cannot be converted to a number, parseFloat() returns NaN.

So, your problem is in variable number_parsed: you don't need to use parseFloat() function

var isNum = function(number) {
    var number_parsed = parseFloat( number ); // remove it
    if (isNaN(number) || typeof number == 'string' ){
          return "enter the number not the string"
    } else if(number_parsed % 2 ===0){ // just use number instead of number_parsed 
        return true;
    } else{   
        return false;
    }
};
isNum('berry');

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.