Checking whether something is a number

Benchmark created by Lea Verou on


Preparation HTML

<script>
  var itIs = 5,
      itsNot = 'foo',
      itsNaN = +'foo';
  
  function test1(val) {
   return typeof val === 'number' && !isNaN(val);
  }
  
  function test2(val) {
   return val + 0 === val;
  }
  
  function test3(val) {
   return Object.prototype.toString.call(val) === '[object Number]' && !isNaN(val);
  }
  
  function test4(val) {
   return val.constructor === Number && !isNaN(val);
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
1
test1(itIs);
test1(itsNot);
test1(itsNaN);
ready
2
test2(itIs);
test2(itsNot);
test2(itsNaN);
ready
3
test3(itIs);
test3(itsNot);
test3(itsNaN);
ready
4
test4(itIs);
test4(itsNot);
test4(itsNaN);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Lea Verou on