1

I have the following function:

    isNumber: function (num) {
        // Return false if num is null or an empty string
        if (num === null || (typeof num === "string" && num.length === 0)) {
            return false;
        }
        var rtn = !isNaN(num)
        return rtn;

    },

This gives me a problem if num is not yet defined. How can I make it return false when num is undefined?

Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427

4 Answers4

1

You could use "loose" comparison when you compare against null:

num == null

This will be true if num is undefined or null (and only then).

You can also simplify the string comparison so that the overall test is:

num == null || num === ''
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

Replace

if (num === null || (typeof num === "string" && num.length === 0))

with

if (num === null || typeof num === "undefined" || (typeof num === "string" && num.length === 0))

as you see, the new condition also handles the case in which num is undefined.

Matteo Tassinari
  • 18,121
  • 8
  • 60
  • 81
0

You can check if no value was passed to the function by testing the array of the arguments passed to the function; so if arguments.length=0 then no arguments were passed to the function and num will not be defined.

You could also do further checks against num !== undefined && num !== null (note that non-identity operator !== is used instead of non-equality operator !=).

Instead you could just check that if you parse the number it is a valid non-infinite number:

isNumber: function (num) {
    if ( arguments.length == 0 )
    {
        return false;
    }
    return !isNaN(parseFloat(num))&&isFinite(num);
}

This checks if:

  • parseFloat(num) evaluates to a valid number; and if
  • isFinite(num) - that valid number is not positive or negative infinity.

If this meets your criteria then you don't need the first check (since parseFloat(undefined) returns NaN) and can simplify the function to:

isNumber: function (num) {
    return !isNaN(parseFloat(num))&&isFinite(num);
}
MT0
  • 143,790
  • 11
  • 59
  • 117
0

See this answer.

<script>
function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

alert(isNumber());            //false
alert(isNumber(10));          //true
alert(isNumber(null));        //false
alert(isNumber(undefined));   //false
</script>
Community
  • 1
  • 1
iForests
  • 6,757
  • 10
  • 42
  • 75