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.

0

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.