Extending Number.prototype in javascript and the Math object?

AnnanFay picture AnnanFay · Mar 7, 2009 · Viewed 19.6k times · Source

I've always wondered why Javascript has the global Math object instead of giving numbers their own methods. Is there a good reason for it?

Also are there any drawbacks (other than efficiency) to doing something like this?:

Number.prototype.round = function(){
    return Math.round(this);
};

Just to make clear, I understand that constants like π need somewhere and functions that are applied on more than one number like min/max. The question was mainly concerning methods which only effect a single number such as round, abs, sin, pow, etc.

Answer

Ferdinand Beyer picture Ferdinand Beyer · Mar 7, 2009

There is no drawback in extending Number.prototype other than confusing other people. What's the point? What is better in using value.round() instead of Math.round(value)?

There are several good reasons for the Math object:

  1. It works for non-numbers, too: Math.round("5") works whereas value.round() won't work when value is a string (for example, the value of a textbox)
  2. Some members of the Math object don't belong to a "primary" number value, like Math.min() or Math.max(). Or do you want to use it like a.max(b)?
  3. Other members are global and do not belong to a specialized number. Examples are constants like Math.PI or the function Math.random().