Why does JavaScript have the Math object?

2693 views javascript
4

In many languages, to find cosine, you use cos(x). But in JavaScript, you must use Math.cos(x). Why doesn't JavaScript spare us the 5 characters in Math., both making it easier to type and easier to read?

I have tried to Google this multiple times, and found no answers. Is there any practical reason for this that I have not yet found?

So far, there are three reasons I can think of:

  1. The creators of JavaScript want to ensure that the math functions do not coincide with other functions users create (Like a function called 'cos()` that calculates, say, cosecant)

  2. The creators of JavaScript thought that Math would make the code more readable

  3. The creators of JavaScript perhaps didn't want any functions that have window as a parent (Though alert and prompt make this unlikely)

answered question

The global scope is already overloaded enough IMO

I'm honestly surprised nobody's asked this before

If you wish to use certain Math functions often and don't like repeating the Math. part, feel free to extract the standalone properties first. const { cos } = Math;

@RedwolfPrograms Stack Overflow isn't a good place for "why did the designers of language X do Y" questions. The motivations behind such decisions are often not public knowledge and SO is a place for solving programming problems, not documenting history.

If you want my guess, it may have something to do with Java's Math class, since the executives in charge of creating JavaScript wanted something that looked like Java.

1 Answer

1

To hold the math functions without polluting the global namespace.

posted this

Have an answer?

JD

Please login first before posting an answer.