1

I coded this:

        isNumberNotZero: function (num) {

            // Return false if num is null, an empty string or zero
            if (num === null || typeof num === "undefined" || (typeof num === "string" && num.length === 0) || num == 0) {
                return false;
            }
            return true;
        },

But is there an easier way to do this. The code I have does not seem very clean.

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

3 Answers3

4

You are doing a lot of checking for things that it is not, when you only care if it is a number greater than zero.

Just:

return typeof a === "number" && a > 0
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

This is from an answer to the famous Validate numbers in JavaScript - IsNumeric() question:

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

Then your test is as simple as combining that function with a > 0:

return isNumber(input) && input > 0;
Community
  • 1
  • 1
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
0

You could use a unary plus operator to convert to an integer, if you want to shorten the code.

This isn't as readable, and only works for integers (e.g., if your number is 0.5, this will treat it as a zero), but it's fast and concise.

function isNumberNotZero(num) {
    return +num !== 0;
}
Tom Pietrosanti
  • 4,184
  • 2
  • 24
  • 29