Why is Math type Object in Javascript?

Asked

Viewed 37 times

1

In literature Math is the type "object", however, the concept of object in its structure is of the key/value type. And I do not see the object structure in Math, need to understand better.

  • And why Math would not be key value? Math.floor, for example, evidence that Math is, in fact, an object, in which case, Math the object and floor a property (which, as a function, can also be called a method - in this case "static" too).

  • Right Elipe, so from what I understood as the concept of Object is key and value (Math = key/floor = value), that would be his reasoning?

1 answer

4


According to the specification, a value of the type "object" is (in free translation):

An object is a collection of properties. [...]

Therefore, Math is an object since it is, in fact, a collection of properties. When you access, for example, Math.floor or Math.PI, of course it is an object (the operator . denotes property access on an object).

Another way to infer that Math is object is to verify that it is none of the primitives of language. Therefore, as Math does not correspond to any other primitive type (undefined, null, boolean, number, bigint, string and symbol), it can only be an object.

It is worth noting that all functions are objects in Javascript. However, the reciprocal is not true, that is, not every object is a function, as is the case of the Math, which is "just" an object.

For more technical details, please refer to Math. And the documentation.


This type of object (such as Math, JSON) were created to serve as "namespace". In versions prior to Ecmascript 2015 (ES6), Javascript did not have a module standard natively. Thus, not to do "ugly" and leave functions like mathematics as abs, floor, ceil, sin etc in the global scope, this type of "namespace object" was created, that is, with the aim of grouping functions "from the same domain" into the same object.

If modules were available from the beginning, you would probably:

import { floor } from 'std:math'; // NÃO EXISTE. Apenas demonstrando uma possibilidade.

floor(4.34); // 4

Instead of:

js
Math.floor(4.34); //4

There is a a proposal (currently in stage 1) to standardize a "standard library" in module format for Javascript. However, it still seems to be quite premature and will probably take some time to move forward.


It should also be noted that the Math is not a function object. This is because it does not implement the internal property [[Call]]. Therefore, Math cannot be invoked (Math() is wrong - and makes no sense). Nor can it be used to build objects with new since it does not implement the internal method [[Construct]].

  • Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.