2

I have problem.

I am writing online JavaScript test, and there is a task to write a function which checks if the value of the parameter is a number. If so, then function must return true.

So I wrote it:

function Numeric(a) {        
  if(isNaN(a)===false)
        return true; 
   else
        throw "Element is not a number";
}

It works fine is JSfiddle, but I don't know why, at that site it is not working. Doesn't pass the test. Any ideas?

RandomUser
  • 63
  • 1
  • 8
  • Then you're probably not getting a number, otherwise it would work ! – adeneo Jul 16 '14 at 13:23
  • 2
    Does it actually want you to throw an error if the parameter is not a number, or just `return false`? – Matt Jul 16 '14 at 13:23
  • http://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric – William Barbosa Jul 16 '14 at 13:24
  • Looks like you really just want a proper `isNumeric()` method, and then just use that in a condition if you need to throw an error. I'm inclined to close this as dupe of http://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric – adeneo Jul 16 '14 at 13:32
  • your code should work, any way you can try checking `typeof(a)==='number'` – Mritunjay Jul 16 '14 at 13:32
  • ... an alternative way to interpret the question (admittedly, how I interpreted it first) is to check that the parameter is a numeric type; in which case your code should be `if (typeof a === 'number')` – Matt Jul 16 '14 at 13:33
  • You might take a look at Underscore.js. It has some nice functions like the one you wrote above. – Upperstage Jul 16 '14 at 13:43

1 Answers1

0

Can we see the call in context?

Also you might want to try

function isNumber(b)
{
    return isNaN(b)||typeof(b)!=="number"?false:true;
}

Basically IF b is NaN OR typeof b is NOT "number" return FALSE ELSE return TRUE

your old versions got confused if you put in true/false, the typeof check will also pick up undefined variables.

Could change false to console.error() but false would make more sense i think for a logical check.

nepeo
  • 509
  • 2
  • 9