[ Why JavaScript Math module name does not follow camelCase? ]
I was sure that JavaScript "official" case for identifiers is camelCase, setInterval()
, .round()
.
So why does Math
start with a capital, then?
Answer 1
Well, Math
is indeed somewhat unique among the host JS modules - Object
, Number
, Date
, RegExp
etc. It's not a function - it's an object, and the next object in its prototype chain is Object.prototype
:
typeof Object; // function
typeof Math; // object
Math.__proto__ === Object.prototype // true
Still, it's a rather unique object, having a fair share of generic JS helper functions and constants attached to it. And it would have been quite inconvenient NOT seeing it clearly stand out among other objects in the source code.
I said 'unique', and it's almost true. ) See, in the whole text of ECMAScript Language specification (edition 5.1) phrase 'a single object' appears exactly twice: first in Math
section (15.8), second - in JSON
section (15.12). So there are actually two such 'service-like' host objects; names of both begin with a capital letter.
Answer 2
Generally things which start with a capital in JS are constructors--they can be invoked with new
to make a new instance of whatever they are:
var o = new Object(),
f = new Function('alert("foo");'),
d = new Date(),
s = new String('foo'),
a = new Array(),
r = new RegExp('/0-9/')
n = new Number('2'),
b = new Boolean(),
e = new Error('bar');
I've always believed Math
is simply a fluke, or was intended to be a constructor and later that was decided against.
However, the spec linked by raina77ow in the answer before mine say, about both Math
and JSON
, that the "value of the [[Class]] internal property" for each is Math
and JSON
, respectively. This got me digging further through the spec where I found:
The value of the [[Class]] internal property is defined by this specification for every kind of built-in object. The value of the [[Class]] internal property of a host object may be any String value except one of "Arguments", "Array", "Boolean", "Date", "Error", "Function", "JSON", "Math", "Number", "Object", "RegExp", and "String". The value of a [[Class]] internal property is used internally to distinguish different kinds of objects. Note that this specification does not provide any means for a program to access that value except through Object.prototype.toString (see 15.2.4.2).
So I think it was simply decided to use a capital for anything in the list of reserved names for "[[Class]] internal property". Any author of any ECMAScript host may add other host objects to the environment they're creating, but may not use those reserved names in their "[[Class]] internal property."
I can only think of one person who can answer to the original intent, however, and I believe he's not saying a lot to the public at the moment.