Search code examples
javascriptprototype

Number.isInteger(this) doesn't work in Number.prototype method


I needed to count decimals and came with this solution (please run the working snippet):

Number.prototype.decimalCounter = function() {
  if (!Number.isInteger(this)) {
    return this.toString().split(".")[1].length;
  } else return "not integer";
}

var x = 3.445;
console.log(x.decimalCounter())
console.log((3).decimalCounter())

And this works well if the number is a float. However, if the number is an integer, it throws an error. I don't know why, because in the first if statement I declared that only integers will fire that block of code, and if you remove the decimals of x variable, it should enter the else clause and print out "not an integer". But it won't work. Can you help me figure out where it's failing?


Solution

  • In sloppy mode, this for a primitive method like decimalCounter will be the primitive wrapped in an object, so the Number.isInteger test fails, because you're not passing it a primitive, but an object.

    console.log(
      Number.isInteger(new Number(5))
    );

    Enable strict mode, and it'll work as desired, because in strict mode, the primitive won't be wrapped when the method is called:

    'use strict';
    
    Number.prototype.decimalCounter = function() {
      if (Number.isInteger(this)) {
        return "not decimal"
      }
      return this.toString().split(".")[1].length;
    }
    
    console.log((3).decimalCounter())
    console.log((3.45678).decimalCounter())