TypedArray.prototype.fill() - JavaScript

TypedArray.prototype.fill()
===========================

The **`fill()`** method of `TypedArray` instances changes all elements within a range of indices in a typed array to a static value. It returns the modified typed array. This method has the same algorithm as `Array.prototype.fill()`.

Try it
------

Syntax
------

```js
fill(value)
fill(value, start)
fill(value, start, end)
```

### Parameters

`value`

Value to fill the typed array with.

`start` Optional

Zero-based index at which to start filling, converted to an integer.

`end` Optional

Zero-based index at which to end filling, converted to an integer. `fill()` fills up to but not including `end`.

### Return value

The modified typed array, filled with `value`.

Description
-----------

See `Array.prototype.fill()` for more details. This method is not generic and can only be called on typed array instances.

Examples
--------

### Using fill()

```js
new Uint8Array([1, 2, 3]).fill(4); // Uint8Array [4, 4, 4]
new Uint8Array([1, 2, 3]).fill(4, 1); // Uint8Array [1, 4, 4]
new Uint8Array([1, 2, 3]).fill(4, 1, 2); // Uint8Array [1, 4, 3]
new Uint8Array([1, 2, 3]).fill(4, 1, 1); // Uint8Array [1, 2, 3]
new Uint8Array([1, 2, 3]).fill(4, -3, -2); // Uint8Array [4, 2, 3]
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.fill |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `TypedArray.prototype.fill` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `Array.prototype.fill()`


TypedArray.prototype.slice() - JavaScript

TypedArray.prototype.slice()
============================

The **`slice()`** method of `TypedArray` instances returns a copy of a portion of a typed array into a new typed array object selected from `start` to `end` (`end` not included) where `start` and `end` represent the index of items in that typed array. The original typed array will not be modified. This method has the same algorithm as `Array.prototype.slice()`.

Try it
------

Syntax
------

```js
slice()
slice(start)
slice(start, end)
```

### Parameters

`start` Optional

Zero-based index at which to start extraction, converted to an integer.

`end` Optional

Zero-based index at which to end extraction, converted to an integer. `slice()` extracts up to but not including `end`.

### Return value

A new typed array containing the extracted elements.

Description
-----------

See `Array.prototype.slice()` for more details. This method is not generic and can only be called on typed array instances.

Examples
--------

### Return a portion of an existing typed array

```js
const uint8 = new Uint8Array([1, 2, 3]);
uint8.slice(1); // Uint8Array [ 2, 3 ]
uint8.slice(2); // Uint8Array [ 3 ]
uint8.slice(-2); // Uint8Array [ 2, 3 ]
uint8.slice(0, 1); // Uint8Array [ 1 ]
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.slice |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `TypedArray.prototype.slice` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `Array.prototype.slice()`
* `String.prototype.slice()`


TypedArray.prototype.toReversed() - JavaScript

TypedArray.prototype.toReversed()
=================================

The **`toReversed()`** method of `TypedArray` instances is the copying counterpart of the `reverse()` method. It returns a new typed array with the elements in reversed order. This method has the same algorithm as `Array.prototype.toReversed()`.

Syntax
------

```js
toReversed()
```

### Parameters

None.

### Return value

A new typed array containing the elements in reversed order.

Description
-----------

See `Array.prototype.toReversed()` for more details. This method is not generic and can only be called on typed array instances.

Examples
--------

### Using toReversed()

```js
const uint8 = new Uint8Array([1, 2, 3]);
const reversedUint8 = uint8.toReversed();
console.log(reversedUint8); // Uint8Array [3, 2, 1]
console.log(uint8); // Uint8Array [1, 2, 3]
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.toreversed |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `TypedArray.prototype.toReversed` in `core-js`
* JavaScript typed arrays guide
* `TypedArray.prototype.reverse()`
* `TypedArray.prototype.toSorted()`
* `TypedArray.prototype.with()`
* `Array.prototype.toReversed()`


Error.prototype.stack - JavaScript

Error.prototype.stack
=====================

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

**Note:** The `stack` property is de facto implemented by all major JavaScript engines, and the JavaScript standards committee is looking to standardize it. You cannot rely on the precise content of the stack string due to implementation inconsistencies, but you can generally assume it exists and use it for debugging purposes.

The non-standard **`stack`** property of an `Error` instance offers a trace of which functions were called, in what order, from which line and file, and with what arguments. The stack string proceeds from the most recent calls to earlier ones, leading back to the original global scope call.

Value
-----

A string.

Because the `stack` property is non-standard, implementations differ about where it's installed.

* In Firefox, it's an accessor property on `Error.prototype`.
* In Chrome and Safari, it's a data property on each `Error` instance, with the descriptor:

| Property attributes of `Error.prototype.stack` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | yes |

Description
-----------

Each JavaScript engine uses its own format for stack traces, but they are fairly consistent in their high-level structure. Every implementation uses a separate line in the stack to represent each function call. The call that directly caused the error is placed at the top, and the call that started the whole call chain is placed at the bottom. Below are some examples of stack traces:

```js
function foo() {
  bar();
}

function bar() {
  baz();
}

function baz() {
  console.log(new Error().stack);
}

foo();
```

```
#### JavaScriptCore
baz@filename.js:10:24
bar@filename.js:6:6
foo@filename.js:2:6
global code@filename.js:13:4

#### SpiderMonkey
baz@filename.js:10:15
bar@filename.js:6:3
foo@filename.js:2:3
@filename.js:13:1

#### V8
Error
    at baz (filename.js:10:15)
    at bar (filename.js:6:3)
    at foo (filename.js:2:3)
    at filename.js:13:1
```

Different engines set this value at different times. Most modern engines set it when the `Error` object is created. This means you can get the full call stack information within a function using the following:

```js
function foo() {
  console.log(new Error().stack);
}
```

Without having to throw an error and then catch it.

In V8, the non-standard `Error.captureStackTrace()`, `Error.stackTraceLimit`, and `Error.prepareStackTrace()` APIs can be used to customize the stack trace. Read the Stack trace API in the V8 docs for more information.

Stack frames can be things other than explicit function calls, too. For example, event listeners, timeout jobs, and promise handlers all begin their own call chain. Source code within `eval()` and `Function` constructor calls also appear in the stack:

```js
console.log(new Function("return new Error('Function failed')")().stack);
console.log("====");
console.log(eval("new Error('eval failed')").stack);
```

```
#### JavaScriptCore
anonymous@
global code@filename.js:1:65
====
eval code@
eval@[native code]
global code@filename.js:3:17

#### SpiderMonkey
anonymous@filename.js line 1 > Function:1:8
@filename.js:1:65

====
@filename.js line 3 > eval:1:1
@filename.js:3:13

#### V8
Error: Function failed
    at eval (eval at <anonymous> (filename.js:1:13), <anonymous>:1:8)
    at filename.js:1:65
====
Error: eval failed
    at eval (eval at <anonymous> (filename.js:3:13), <anonymous>:1:1)
    at filename.js:3:13
```

In Firefox, you can use the `//# sourceURL` directive to name an eval source. See the Firefox Debug eval sources docs and the Naming `eval` Scripts with the `//# sourceURL` Directive blog post for more details.

Examples
--------

### Using the stack property

The following script demonstrates how to use the `stack` property to output a stack trace into your browser window. You can use this to check what your browser's stack structure looks like.
```

<div id="output"></div>
```

```
#output {
  white-space: pre;
  font-family: monospace;
}
```

```js
function trace() {
  throw new Error("trace() failed");
}
function b() {
  trace();
}
function a() {
  b(3, 4, "\n\n", undefined, {});
}
try {
  a("first call, firstarg");
} catch (e) {
  document.getElementById("output").textContent = e.stack;
}
```

Specifications
--------------

Not part of any standard.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* TraceKit on GitHub
* stacktrace.js on GitHub
* Stack trace API in the V8 docs


Error() constructor - JavaScript

Error() constructor
===================

The **`Error()`** constructor creates `Error` objects.

Syntax
------

```js
new Error()
new Error(message)
new Error(message, options)
new Error(message, fileName)
new Error(message, fileName, lineNumber)

Error()
Error(message)
Error(message, options)
Error(message, fileName)
Error(message, fileName, lineNumber)
```

**Note:** `Error()` can be called with or without `new`. Both create a new `Error` instance.

### Parameters

`message` Optional

A human-readable description of the error.

`options` Optional

An object that has the following properties:

`cause` Optional

A value indicating the specific cause of the error, reflected in the `cause` property. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.

`fileName` Optional
Non-standard

The path to the file that raised this error, reflected in the `fileName` property. Defaults to the name of the file containing the code that called the `Error()` constructor.

`lineNumber` Optional
Non-standard

The line number within the file on which the error was raised, reflected in the `lineNumber` property. Defaults to the line number containing the `Error()` constructor invocation.

Examples
--------

### Function call or new construction

 When `Error` is used like a function, that is without `new`, it will return an `Error` object.
 Therefore, a mere call to `Error` will produce the same output that constructing an `Error` object via the `new` keyword would.

```js
const x = Error("I was created using a function call!");

// above has the same functionality as following
const y = new Error('I was constructed via the "new" keyword!');
```

### Rethrowing an error with a cause

 It is sometimes useful to catch an error and re-throw it with a new message.
 In this case you should pass the original error into the constructor for the new `Error`, as shown.

```js
try {
  frameworkThatCanThrow();
} catch (err) {
  throw new Error("New error message", { cause: err });
}
```

For a more detailed example see Error > Differentiate between similar errors.

### Omitting options argument

JavaScript only tries to read `options.cause` if `options` is an object — this avoids ambiguity with the other non-standard `Error(message, fileName, lineNumber)` signature, which requires the second parameter to be a string. If you omit `options`, pass a primitive value as `options`, or pass an object without the `cause` property, then the created `Error` object will have no `cause` property.

```js
// Omitting options
const error1 = new Error("Error message");
console.log("cause" in error1); // false

// Passing a primitive value
const error2 = new Error("Error message", "");
console.log("cause" in error2); // false

// Passing an object without a cause property
const error3 = new Error("Error message", { details: "http error" });
console.log("cause" in error3); // false
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-error-constructor |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Error` with `cause` support in `core-js`
* `throw`
* `try...catch`
* Error causes on v8.dev (2021)


Error.prototype.toString() - JavaScript

Error.prototype.toString()
==========================

The **`toString()`** method of `Error` instances returns a string representing this error.

Syntax
------

```js
toString()
```

### Parameters

None.

### Return value

A string representing the specified `Error` object.

Description
-----------

 The `Error` object overrides the `Object.prototype.toString()`
 method inherited by all objects. Its semantics are as follows:

```js
Error.prototype.toString = function () {
  if (
    this === null ||
    (typeof this !== "object" && typeof this !== "function")
  ) {
    throw new TypeError();
  }
  let name = this.name;
  name = name === undefined ? "Error" : `${name}`;
  let msg = this.message;
  msg = msg === undefined ? "" : `${msg}`;
  if (name === "") {
    return msg;
  }
  if (msg === "") {
    return name;
  }
  return `${name}: ${msg}`;
};
```

Examples
--------

### Using toString()

```js
const e1 = new Error("fatal error");
console.log(e1.toString()); // "Error: fatal error"

const e2 = new Error("fatal error");
e2.name = undefined;
console.log(e2.toString()); // "Error: fatal error"

const e3 = new Error("fatal error");
e3.name = "";
console.log(e3.toString()); // "fatal error"

const e4 = new Error("fatal error");
e4.name = "";
e4.message = undefined;
console.log(e4.toString()); // ""

const e5 = new Error("fatal error");
e5.name = "hello";
e5.message = undefined;
console.log(e5.toString()); // "hello"
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-error.prototype.tostring |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Error.prototype.toString` with many bug fixes in `core-js`


Error: lineNumber - JavaScript

Error: lineNumber
=================

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`lineNumber`** data property of an `Error` instance contains the line number in the file that raised this error.

Value
-----

A positive integer.

| Property attributes of `Error: lineNumber` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | yes |

Examples
--------

### Using lineNumber

```js
try {
  throw new Error("Could not parse input");
} catch (err) {
  console.log(err.lineNumber); // 2
}
```

### Alternative example using error event

```js
window.addEventListener("error", (e) => {
  console.log(e.lineNumber); // 5
});
const e = new Error("Could not parse input");
throw e;
```

This is not a standard feature and lacks widespread support. See the browser compatibility table below.

Specifications
--------------

Not part of any standard.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Error.prototype.stack`
* `Error.prototype.columnNumber`
* `Error.prototype.fileName`


Error.prototype.name - JavaScript

Error.prototype.name
====================

The **`name`** data property of `Error.prototype` is shared by all `Error` instances. It represents the name for the type of error. For `Error.prototype.name`, the initial value is `"Error"`. Subclasses like `TypeError` and `SyntaxError` provide their own `name` properties.

Value
-----

A string. For `Error.prototype.name`, the initial value is `"Error"`.

| Property attributes of `Error.prototype.name` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | yes |

Description
-----------

By default, `Error` instances are given the name "Error". The `name` property, in addition to the `message` property, is used by the `Error.prototype.toString()` method to create a string representation of the error.

Examples
--------

### Throwing a custom error

```js
const e = new Error("Malformed input"); // e.name is 'Error'

e.name = "ParseError";
throw e;
// e.toString() would return 'ParseError: Malformed input'
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-error.prototype.name |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Error.prototype.message`
* `Error.prototype.toString()`


Error: fileName - JavaScript

Error: fileName
===============

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`fileName`** data property of an `Error` instance contains the path to the file that raised this error.

Value
-----

A string.

| Property attributes of `Error: fileName` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | yes |

Description
-----------

This non-standard property contains the path to the file that raised this error. If called from a debugger context, the Firefox Developer Tools for example, "debugger eval code" is returned.

Examples
--------

### Using fileName

```js
const e = new Error("Could not parse input");
throw e;
// e.fileName could look like "file:///C:/example.html"
```

Specifications
--------------

Not part of any standard.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Error.prototype.stack`
* `Error.prototype.columnNumber`
* `Error.prototype.lineNumber`


Error: message - JavaScript

Error: message
==============

The **`message`** data property of an `Error` instance is a human-readable description of the error.

Value
-----

A string corresponding to the value passed to the `Error()` constructor as the first argument.

| Property attributes of `Error: message` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | yes |

Description
-----------

This property contains a brief description of the error if one is available or has been set. The `message` property combined with the `name` property is used by the `Error.prototype.toString()` method to create a string representation of the Error.

By default, the `message` property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the `Error` constructor.

Examples
--------

### Throwing a custom error

```js
const e = new Error("Could not parse input");
// e.message is 'Could not parse input'
throw e;
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-error.prototype.message |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Error.prototype.name`
* `Error.prototype.toString()`


Error: cause - JavaScript

Error: cause
============

The **`cause`** data property of an `Error` instance indicates the specific original cause of the error.

It is used when catching and re-throwing an error with a more-specific or useful error message in order to still have access to the original error.

Value
-----

The value that was passed to the `Error()` constructor in the `options.cause` argument. It may not be present.

| Property attributes of `Error: cause` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | yes |

Description
-----------

The value of `cause` can be of any type. You should not make assumptions that the error you caught has an `Error` as its `cause`, in the same way that you cannot be sure the variable bound in the `catch` statement is an `Error` either. The "Providing structured data as the error cause" example below shows a case where a non-error is deliberately provided as the cause.

Examples
--------

### Rethrowing an error with a cause

 It is sometimes useful to catch an error and re-throw it with a new message.
 In this case you should pass the original error into the constructor for the new `Error`, as shown.

```js
try {
  connectToDatabase();
} catch (err) {
  throw new Error("Connecting to database failed.", { cause: err });
}
```

For a more detailed example see Error > Differentiate between similar errors.

### Providing structured data as the error cause

Error messages written for human consumption may be inappropriate for machine parsing — since they're subject to rewording or punctuation changes that may break any existing parsing written to consume them. So when throwing an error from a function, as an alternative to a human-readable error message, you can instead provide the cause as structured data, for machine parsing.

```js
function makeRSA(p, q) {
  if (!Number.isInteger(p) || !Number.isInteger(q)) {
    throw new Error("RSA key generation requires integer inputs.", {
      cause: { code: "NonInteger", values: [p, q] },
    });
  }
  if (!areCoprime(p, q)) {
    throw new Error("RSA key generation requires two co-prime integers.", {
      cause: { code: "NonCoprime", values: [p, q] },
    });
  }
  // rsa algorithm…
}
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-installerrorcause |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Error.prototype.message`
* `Error.prototype.toString()`


Error: columnNumber - JavaScript

Error: columnNumber
===================

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`columnNumber`** data property of an `Error` instance contains the column number in the line of the file that raised this error.

Value
-----

A positive integer.

| Property attributes of `Error: columnNumber` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | yes |

Examples
--------

### Using columnNumber

```js
try {
  throw new Error("Could not parse input");
} catch (err) {
  console.log(err.columnNumber); // 9
}
```

Specifications
--------------

Not part of any standard.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Error.prototype.stack`
* `Error.prototype.lineNumber`
* `Error.prototype.fileName`


Math.sign() - JavaScript

Math.sign()
===========

The **`Math.sign()`** static method returns 1 or -1, indicating the sign of the number passed as argument. If the input is 0 or -0, it will be returned as-is.

Try it
------

Syntax
------

```js
Math.sign(x)
```

### Parameters

`x`

A number.

### Return value

A number representing the sign of `x`:

* If `x` is positive, returns `1`.
* If `x` is negative, returns `-1`.
* If `x` is positive zero, returns `0`.
* If `x` is negative zero, returns `-0`.
* Otherwise, returns `NaN`.
Description
-----------

Because `sign()` is a static method of `Math`, you always use it as `Math.sign()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.sign()

```js
Math.sign(3); // 1
Math.sign(-3); // -1
Math.sign("-3"); // -1
Math.sign(0); // 0
Math.sign(-0); // -0
Math.sign(NaN); // NaN
Math.sign("foo"); // NaN
Math.sign(); // NaN
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.sign |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Math.sign` in `core-js`
* `Math.abs()`
* `Math.ceil()`
* `Math.floor()`
* `Math.round()`
* `Math.trunc()`


Math.LN2 - JavaScript

Math.LN2
========

The **`Math.LN2`** static data property represents the natural logarithm of 2, approximately 0.693:

Try it
------

Value
-----

𝙼𝚊𝚝𝚑.𝙻𝙽𝟸
=
ln
(
2
)
≈
0.693

\mathtt{\mi{Math.LN2}} = \ln(2) \approx 0.693

| Property attributes of `Math.LN2` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

Description
-----------

Because `LN2` is a static property of `Math`, you always use it as `Math.LN2`, rather than as a property of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.LN2

The following function returns the natural log of 2:

```js
function getNatLog2() {
  return Math.LN2;
}

getNatLog2(); // 0.6931471805599453
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.ln2 |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.exp()`
* `Math.log()`
* `Math.log2()`


Math.expm1() - JavaScript

Math.expm1()
============

The **`Math.expm1()`** static method returns e raised to the power of a number, subtracted by 1. That is

𝙼𝚊𝚝𝚑.𝚎𝚡𝚙𝚖𝟷
(
𝚡
)

=

e
x

−
1

\mathtt{\operatorname{Math.expm1}(x)} = \mathrm{e}^x - 1

Try it
------

Syntax
------

```js
Math.expm1(x)
```

### Parameters

`x`

A number.

### Return value

A number representing ex - 1, where e is the base of the natural logarithm.

Description
-----------

For very small values of *x*, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 = 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off.

When you calculate

e
x

\mathrm{e}^x

 where x is a number very close to 0, you should get an answer very close to 1 + x, because

lim

x
→
0

e
x

−
1

x

=
1

\lim\_{x \to 0} \frac{\mathrm{e}^x - 1}{x} = 1

. If you calculate `Math.exp(1.1111111111e-15) - 1`, you should get an answer close to `1.1111111111e-15`. Instead, due to the highest significant figure in the result of `Math.exp` being the units digit `1`, the final value ends up being `1.1102230246251565e-15`, with only 3 correct digits. If, instead, you calculate `Math.exp1m(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111111000007e-15`, with 11 correct digits of precision.

Because `expm1()` is a static method of `Math`, you always use it as `Math.expm1()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.expm1()

```js
Math.expm1(-Infinity); // -1
Math.expm1(-1); // -0.6321205588285577
Math.expm1(-0); // -0
Math.expm1(0); // 0
Math.expm1(1); // 1.718281828459045
Math.expm1(Infinity); // Infinity
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.expm1 |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Math.expm1` in `core-js`
* `Math.E`
* `Math.exp()`
* `Math.log()`
* `Math.log10()`
* `Math.log1p()`
* `Math.log2()`
* `Math.pow()`


Math.atanh() - JavaScript

Math.atanh()
============

The **`Math.atanh()`** static method returns the inverse hyperbolic tangent of a number. That is,

∀
x
∊
(

−
1

,
1
)
,

𝙼𝚊𝚝𝚑.𝚊𝚝𝚊𝚗𝚑
(
𝚡
)

=
artanh
(
x
)
=
the unique
y
 such that
tanh
(
y
)
=
x

=

1
2

ln

(

1
+
x

1
−
x

)

\begin{aligned}\forall x \in ({-1}, 1),;\mathtt{\operatorname{Math.atanh}(x)} &= \operatorname{artanh}(x) = \text{the unique } y \text{ such that } \tanh(y) = x \&= \frac{1}{2},\ln\left(\frac{1+x}{1-x}\right)\end{aligned}

Try it
------

Syntax
------

```js
Math.atanh(x)
```

### Parameters

`x`

A number between -1 and 1, inclusive.

### Return value

The inverse hyperbolic tangent of `x`. If `x` is 1, returns `Infinity`. If `x` is -1, returns `-Infinity`. If `x` is less than -1 or greater than 1, returns `NaN`.

Description
-----------

Because `atanh()` is a static method of `Math`, you always use it as `Math.atanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.atanh()

```js
Math.atanh(-2); // NaN
Math.atanh(-1); // -Infinity
Math.atanh(-0); // -0
Math.atanh(0); // 0
Math.atanh(0.5); // 0.5493061443340548
Math.atanh(1); // Infinity
Math.atanh(2); // NaN
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.atanh |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Math.atanh` in `core-js`
* `Math.acosh()`
* `Math.asinh()`
* `Math.cosh()`
* `Math.sinh()`
* `Math.tanh()`


Math.asinh() - JavaScript

Math.asinh()
============

The **`Math.asinh()`** static method returns the inverse hyperbolic sine of a number. That is,

𝙼𝚊𝚝𝚑.𝚊𝚜𝚒𝚗𝚑
(
𝚡
)

=
arsinh
(
x
)
=
the unique
y
 such that
sinh
(
y
)
=
x

=
ln

(

x
+

x
2

+
1

)

\begin{aligned}\mathtt{\operatorname{Math.asinh}(x)} &= \operatorname{arsinh}(x) = \text{the unique } y \text{ such that } \sinh(y) = x \&= \ln\left(x + \sqrt{x^2 + 1}\right)\end{aligned}

Try it
------

Syntax
------

```js
Math.asinh(x)
```

### Parameters

`x`

A number.

### Return value

The inverse hyperbolic sine of `x`.

Description
-----------

Because `asinh()` is a static method of `Math`, you always use it as `Math.asinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.asinh()

```js
Math.asinh(-Infinity); // -Infinity
Math.asinh(-1); // -0.881373587019543
Math.asinh(-0); // -0
Math.asinh(0); // 0
Math.asinh(1); // 0.881373587019543
Math.asinh(Infinity); // Infinity
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.asinh |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Math.asinh` in `core-js`
* `Math.acosh()`
* `Math.atanh()`
* `Math.cosh()`
* `Math.sinh()`
* `Math.tanh()`


Math.log1p() - JavaScript

Math.log1p()
============

The **`Math.log1p()`** static method returns the natural logarithm (base e) of `1 + x`, where `x` is the argument. That is:

∀
x
>
−
1
,

𝙼𝚊𝚝𝚑.𝚕𝚘𝚐𝟷𝚙
(
𝚡
)

=
ln
(
1
+
x
)

\forall x > -1,;\mathtt{\operatorname{Math.log1p}(x)} = \ln(1 + x)

Try it
------

Syntax
------

```js
Math.log1p(x)
```

### Parameters

`x`

A number greater than or equal to -1.

### Return value

The natural logarithm (base e) of `x + 1`. If `x` is -1, returns `-Infinity`. If `x < -1`, returns `NaN`.

Description
-----------

For very small values of *x*, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 = 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off.

When you calculate log(1 + *x*) where *x* is a small positive number, you should get an answer very close to *x*, because

lim

x
→
0

log

(
1
+
x
)

x

=
1

\lim\_{x \to 0} \frac{\log(1+x)}{x} = 1

. If you calculate `Math.log(1 + 1.1111111111e-15)`, you should get an answer close to `1.1111111111e-15`. Instead, you will end up taking the logarithm of `1.00000000000000111022` (the roundoff is in binary, so sometimes it gets ugly), and get the answer 1.11022…e-15, with only 3 correct digits. If, instead, you calculate `Math.log1p(1.1111111111e-15)`, you will get a much more accurate answer `1.1111111110999995e-15`, with 15 correct digits of precision (actually 16 in this case).

If the value of `x` is less than -1, the return value is always `NaN`.

Because `log1p()` is a static method of `Math`, you always use it as `Math.log1p()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.log1p()

```js
Math.log1p(-2); // NaN
Math.log1p(-1); // -Infinity
Math.log1p(-0); // -0
Math.log1p(0); // 0
Math.log1p(1); // 0.6931471805599453
Math.log1p(Infinity); // Infinity
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.log1p |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Math.log1p` in `core-js`
* `Math.exp()`
* `Math.log()`
* `Math.expm1()`
* `Math.log10()`
* `Math.log2()`
* `Math.pow()`


Math.SQRT2 - JavaScript

Math.SQRT2
==========

The **`Math.SQRT2`** static data property represents the square root of 2, approximately 1.414.

Try it
------

Value
-----

𝙼𝚊𝚝𝚑.𝚂𝚀𝚁𝚃𝟸
=

2

≈
1.414

\mathtt{\mi{Math.SQRT2}} = \sqrt{2} \approx 1.414

| Property attributes of `Math.SQRT2` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

Description
-----------

`Math.SQRT2` is a constant and a more performant equivalent to `Math.sqrt(2)`.

Because `SQRT2` is a static property of `Math`, you always use it as `Math.SQRT2`, rather than as a property of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.SQRT2

The following function returns the square root of 2:

```js
function getRoot2() {
  return Math.SQRT2;
}

getRoot2(); // 1.4142135623730951
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.sqrt2 |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.pow()`
* `Math.sqrt()`


Math.LN10 - JavaScript

Math.LN10
=========

The **`Math.LN10`** static data property represents the natural logarithm of 10, approximately 2.302.

Try it
------

Value
-----

𝙼𝚊𝚝𝚑.𝙻𝙽𝟷𝟶
=
ln
(
10
)
≈
2.302

\mathtt{\mi{Math.LN10}} = \ln(10) \approx 2.302

| Property attributes of `Math.LN10` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

Description
-----------

Because `LN10` is a static property of `Math`, you always use it as `Math.LN10`, rather than as a property of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.LN10

The following function returns the natural log of 10:

```js
function getNatLog10() {
  return Math.LN10;
}

getNatLog10(); // 2.302585092994046
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.ln10 |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.exp()`
* `Math.log()`
* `Math.log10()`


Math.hypot() - JavaScript

Math.hypot()
============

The **`Math.hypot()`** static method returns the square root of the sum of squares of its arguments. That is,

𝙼𝚊𝚝𝚑.𝚑𝚢𝚙𝚘𝚝
(

v
1

,

v
2

,
…
,

v
n

)

=

∑

i
=
1

n

v
i
2

=

v
1
2

+

v
2
2

+
…
+

v
n
2

\mathtt{\operatorname{Math.hypot}(v\_1, v\_2, \dots, v\_n)} = \sqrt{\sum\_{i=1}^n v\_i^2} = \sqrt{v\_1^2 + v\_2^2 + \dots + v\_n^2}

Try it
------

Syntax
------

```js
Math.hypot()
Math.hypot(value1)
Math.hypot(value1, value2)
Math.hypot(value1, value2, /\* …, \*/ valueN)
```

### Parameters

`value1`, …, `valueN`

Numbers.

### Return value

The square root of the sum of squares of the given arguments. Returns `Infinity` if any of the arguments is ±Infinity. Otherwise, if at least one of the arguments is or is converted to `NaN`, returns `NaN`. Returns `0` if no arguments are given or all arguments are ±0.

Description
-----------

Calculating the hypotenuse of a right triangle, or the magnitude of a complex number, uses the formula `Math.sqrt(v1*v1 + v2*v2)`, where v1 and v2 are the lengths of the triangle's legs, or the complex number's real and complex components. The corresponding distance in 2 or more dimensions can be calculated by adding more squares under the square root: `Math.sqrt(v1*v1 + v2*v2 + v3*v3 + v4*v4)`.

This function makes this calculation easier and faster; you call `Math.hypot(v1, v2)`, or `Math.hypot(v1, /* …, */, vN)`.

`Math.hypot` also avoids overflow/underflow problems if the magnitude of your numbers is very large. The largest number you can represent in JS is `Number.MAX_VALUE`, which is around 10308. If your numbers are larger than about 10154, taking the square of them will result in Infinity. For example, `Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinity`. If you use `hypot()` instead, you get a better answer: `Math.hypot(1e200, 1e200) = 1.4142...e+200` . This is also true with very small numbers. `Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0`, but `Math.hypot(1e-200, 1e-200) = 1.4142...e-200`.

With one argument, `Math.hypot()` is equivalent to `Math.abs()`. `Math.hypot.length` is 2, which weakly signals that it's designed to handle at least two parameters.

Because `hypot()` is a static method of `Math`, you always use it as `Math.hypot()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.hypot()

```js
Math.hypot(3, 4); // 5
Math.hypot(3, 4, 5); // 7.0710678118654755
Math.hypot(); // 0
Math.hypot(NaN); // NaN
Math.hypot(NaN, Infinity); // Infinity
Math.hypot(3, 4, "foo"); // NaN, since +'foo' => NaN
Math.hypot(3, 4, "5"); // 7.0710678118654755, +'5' => 5
Math.hypot(-3); // 3, the same as Math.abs(-3)
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.hypot |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Math.hypot` in `core-js`
* `Math.abs()`
* `Math.pow()`
* `Math.sqrt()`


Math.tanh() - JavaScript

Math.tanh()
===========

The **`Math.tanh()`** static method returns the hyperbolic tangent of a number. That is,

𝙼𝚊𝚝𝚑.𝚝𝚊𝚗𝚑
(
𝚡
)

=
tanh
(
x
)
=

sinh
(
x
)

cosh
(
x
)

=

e
x

−

e

−
x

e
x

+

e

−
x

=

e

2
x

−
1

e

2
x

+
1

\mathtt{\operatorname{Math.tanh}(x)} = \tanh(x) = \frac{\sinh(x)}{\cosh(x)} = \frac{\mathrm{e}^x - \mathrm{e}^{-x}}{\mathrm{e}^x + \mathrm{e}^{-x}} = \frac{\mathrm{e}^{2x} - 1}{\mathrm{e}^{2x}+1}

Try it
------

Syntax
------

```js
Math.tanh(x)
```

### Parameters

`x`

A number.

### Return value

The hyperbolic tangent of `x`.

Description
-----------

Because `tanh()` is a static method of `Math`, you always use it as `Math.tanh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.tanh()

```js
Math.tanh(-Infinity); // -1
Math.tanh(-0); // -0
Math.tanh(0); // 0
Math.tanh(1); // 0.7615941559557649
Math.tanh(Infinity); // 1
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.tanh |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Math.tanh` in `core-js`
* `Math.acosh()`
* `Math.asinh()`
* `Math.atanh()`
* `Math.cosh()`
* `Math.sinh()`


Math.floor() - JavaScript

Math.floor()
============

The **`Math.floor()`** static method always rounds down and returns the largest integer less than or equal to a given number.

Try it
------

Syntax
------

```js
Math.floor(x)
```

### Parameters

`x`

A number.

### Return value

The largest integer smaller than or equal to `x`. It's the same value as `-Math.ceil(-x)`.

Description
-----------

Because `floor()` is a static method of `Math`, you always use it as `Math.floor()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.floor()

```js
Math.floor(-Infinity); // -Infinity
Math.floor(-45.95); // -46
Math.floor(-45.05); // -46
Math.floor(-0); // -0
Math.floor(0); // 0
Math.floor(4); // 4
Math.floor(45.05); // 45
Math.floor(45.95); // 45
Math.floor(Infinity); // Infinity
```

### Decimal adjustment

In this example, we implement a method called `decimalAdjust()` that is an enhancement method of `Math.floor()`, `Math.ceil()`, and `Math.round()`. While the three `Math` functions always adjust the input to the units digit, `decimalAdjust` accepts an `exp` parameter that specifies the number of digits to the left of the decimal point to which the number should be adjusted. For example, `-1` means it would leave one digit after the decimal point (as in "× 10-1"). In addition, it allows you to select the means of adjustment — `round`, `floor`, or `ceil` — through the `type` parameter.

It does so by multiplying the number by a power of 10, then rounding the result to the nearest integer, then dividing by the power of 10. To better preserve precision, it takes advantage of Number's `toString()` method, which represents large or small numbers in scientific notation (like `6.02e23`).

```js
/\*\*
 \* Adjusts a number to the specified digit.
 \*
 \* @param {"round" | "floor" | "ceil"} type The type of adjustment.
 \* @param {number} value The number.
 \* @param {number} exp The exponent (the 10 logarithm of the adjustment base).
 \* @returns {number} The adjusted value.
 \*/
function decimalAdjust(type, value, exp) {
  type = String(type);
  if (!["round", "floor", "ceil"].includes(type)) {
    throw new TypeError(
      "The type of decimal adjustment must be one of 'round', 'floor', or 'ceil'.",
    );
  }
  exp = Number(exp);
  value = Number(value);
  if (exp % 1 !== 0 || Number.isNaN(value)) {
    return NaN;
  } else if (exp === 0) {
    return Math[type](value);
  }
  const [magnitude, exponent = 0] = value.toString().split("e");
  const adjustedValue = Math[type](`${magnitude}e${exponent - exp}`);
  // Shift back
  const [newMagnitude, newExponent = 0] = adjustedValue.toString().split("e");
  return Number(`${newMagnitude}e${+newExponent + exp}`);
}

// Decimal round
const round10 = (value, exp) => decimalAdjust("round", value, exp);
// Decimal floor
const floor10 = (value, exp) => decimalAdjust("floor", value, exp);
// Decimal ceil
const ceil10 = (value, exp) => decimalAdjust("ceil", value, exp);

// Round
round10(55.55, -1); // 55.6
round10(55.549, -1); // 55.5
round10(55, 1); // 60
round10(54.9, 1); // 50
round10(-55.55, -1); // -55.5
round10(-55.551, -1); // -55.6
round10(-55, 1); // -50
round10(-55.1, 1); // -60
// Floor
floor10(55.59, -1); // 55.5
floor10(59, 1); // 50
floor10(-55.51, -1); // -55.6
floor10(-51, 1); // -60
// Ceil
ceil10(55.51, -1); // 55.6
ceil10(51, 1); // 60
ceil10(-55.59, -1); // -55.5
ceil10(-59, 1); // -50
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.floor |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.abs()`
* `Math.ceil()`
* `Math.round()`
* `Math.sign()`
* `Math.trunc()`


Math.ceil() - JavaScript

Math.ceil()
===========

The **`Math.ceil()`** static method always rounds up and returns the smallest integer greater than or equal to a given number.

Try it
------

Syntax
------

```js
Math.ceil(x)
```

### Parameters

`x`

A number.

### Return value

The smallest integer greater than or equal to `x`. It's the same value as `-Math.floor(-x)`.

Description
-----------

Because `ceil()` is a static method of `Math`, you always use it as `Math.ceil()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.ceil()

```js
Math.ceil(-Infinity); // -Infinity
Math.ceil(-7.004); // -7
Math.ceil(-4); // -4
Math.ceil(-0.95); // -0
Math.ceil(-0); // -0
Math.ceil(0); // 0
Math.ceil(0.95); // 1
Math.ceil(4); // 4
Math.ceil(7.004); // 8
Math.ceil(Infinity); // Infinity
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.ceil |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.abs()`
* `Math.floor()`
* `Math.round()`
* `Math.sign()`
* `Math.trunc()`


Math.trunc() - JavaScript

Math.trunc()
============

The **`Math.trunc()`** static method returns the integer part of a number by removing any fractional digits.

Try it
------

Syntax
------

```js
Math.trunc(x)
```

### Parameters

`x`

A number.

### Return value

The integer part of `x`.

Description
-----------

Unlike the other three `Math` methods: `Math.floor()`, `Math.ceil()` and `Math.round()`, the way `Math.trunc()` works is very simple. It *truncates* (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number.

Because `trunc()` is a static method of `Math`, you always use it as `Math.trunc()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.trunc()

```js
Math.trunc(-Infinity); // -Infinity
Math.trunc("-1.123"); // -1
Math.trunc(-0.123); // -0
Math.trunc(-0); // -0
Math.trunc(0); // 0
Math.trunc(0.123); // 0
Math.trunc(13.37); // 13
Math.trunc(42.84); // 42
Math.trunc(Infinity); // Infinity
```

### Using bitwise no-ops to truncate numbers

**Warning:** This is not a polyfill for `Math.trunc()` because of non-negligible edge cases.

Bitwise operations convert their operands to 32-bit integers, which people have historically taken advantage of to truncate float-point numbers. Common techniques include:

```js
const original = 3.14;
const truncated1 = ~~original; // Double negation
const truncated2 = original & -1; // Bitwise AND with -1
const truncated3 = original | 0; // Bitwise OR with 0
const truncated4 = original ^ 0; // Bitwise XOR with 0
const truncated5 = original >> 0; // Bitwise shifting by 0
```

Beware that this is essentially `toInt32`, which is not the same as `Math.trunc`. When the value does not satisfy -231 - 1 < `value` < 231 (-2147483649 < `value` < 2147483648), the conversion would overflow.

```js
const a = ~~2147483648; // -2147483648
const b = ~~-2147483649; // 2147483647
const c = ~~4294967296; // 0
```

Only use `~~` as a substitution for `Math.trunc()` when you are confident that the range of input falls within the range of 32-bit integers.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.trunc |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Math.trunc` in `core-js`
* `Math.abs()`
* `Math.ceil()`
* `Math.floor()`
* `Math.round()`
* `Math.sign()`


Math.exp() - JavaScript

Math.exp()
==========

The **`Math.exp()`** static method returns e raised to the power of a number. That is

𝙼𝚊𝚝𝚑.𝚎𝚡𝚙
(
𝚡
)

=

e
x

\mathtt{\operatorname{Math.exp}(x)} = \mathrm{e}^x

Try it
------

Syntax
------

```js
Math.exp(x)
```

### Parameters

`x`

A number.

### Return value

A nonnegative number representing ex, where e is the base of the natural logarithm.

Description
-----------

Because `exp()` is a static method of `Math`, you always use it as `Math.exp()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Beware that `e` to the power of a number very close to 0 will be very close to 1 and suffer from loss of precision. In this case, you may want to use `Math.expm1` instead, and obtain a much higher-precision fractional part of the answer.

Examples
--------

### Using Math.exp()

```js
Math.exp(-Infinity); // 0
Math.exp(-1); // 0.36787944117144233
Math.exp(0); // 1
Math.exp(1); // 2.718281828459045
Math.exp(Infinity); // Infinity
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.exp |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.E`
* `Math.expm1()`
* `Math.log()`
* `Math.log10()`
* `Math.log1p()`
* `Math.log2()`
* `Math.pow()`


Math.PI - JavaScript

Math.PI
=======

The **`Math.PI`** static data property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159.

Try it
------

Value
-----

𝙼𝚊𝚝𝚑.𝙿𝙸
=
π
≈
3.14159

\mathtt{\mi{Math.PI}} = \pi \approx 3.14159

| Property attributes of `Math.PI` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

Description
-----------

Because `PI` is a static property of `Math`, you always use it as `Math.PI`, rather than as a property of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.PI

The following function uses `Math.PI` to calculate the circumference of a circle with a passed radius.

```js
function calculateCircumference(radius) {
  return Math.PI \* (radius + radius);
}

calculateCircumference(1); // 6.283185307179586
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.pi |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math`


Math.sinh() - JavaScript

Math.sinh()
===========

The **`Math.sinh()`** static method returns the hyperbolic sine of a number. That is,

𝙼𝚊𝚝𝚑.𝚜𝚒𝚗𝚑
(
𝚡
)

=
sinh
(
x
)
=

e
x

−

e

−
x

2

\mathtt{\operatorname{Math.sinh}(x)} = \sinh(x) = \frac{\mathrm{e}^x - \mathrm{e}^{-x}}{2}

Try it
------

Syntax
------

```js
Math.sinh(x)
```

### Parameters

`x`

A number.

### Return value

The hyperbolic sine of `x`.

Description
-----------

Because `sinh()` is a static method of `Math`, you always use it as `Math.sinh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.sinh()

```js
Math.sinh(-Infinity); // -Infinity
Math.sinh(-0); // -0
Math.sinh(0); // 0
Math.sinh(1); // 1.1752011936438014
Math.sinh(Infinity); // Infinity
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.sinh |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Math.sinh` in `core-js`
* `Math.acosh()`
* `Math.asinh()`
* `Math.atanh()`
* `Math.cosh()`
* `Math.tanh()`


Math.atan2() - JavaScript

Math.atan2()
============

The **`Math.atan2()`** static method returns the angle in the plane (in radians) between the positive x-axis and the ray from (0, 0) to the point (x, y), for `Math.atan2(y, x)`.

Try it
------

Syntax
------

```js
Math.atan2(y, x)
```

### Parameters

`y`

The y coordinate of the point.

`x`

The x coordinate of the point.

### Return value

The angle in radians (between -π and π, inclusive) between the positive x-axis and the ray from (0, 0) to the point (x, y).

Description
-----------

The `Math.atan2()` method measures the counterclockwise angle θ, in radians, between the positive x-axis and the point `(x, y)`. Note that the arguments to this function pass the y-coordinate first and the x-coordinate second.

![A simple diagram showing the angle returned by atan2(y, x)](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2/atan2.png)

`Math.atan2()` is passed separate `x` and `y` arguments, while `Math.atan()` is passed the ratio of those two arguments. `Math.atan2(y, x)` differs from `Math.atan(y / x)` in the following cases:

| `x` | `y` | `Math.atan2(y, x)` | `Math.atan(y / x)` |
| --- | --- | --- | --- |
| `Infinity` | `Infinity` | π / 4 | `NaN` |
| `Infinity` | `-Infinity` | -π / 4 | `NaN` |
| `-Infinity` | `Infinity` | 3π / 4 | `NaN` |
| `-Infinity` | `-Infinity` | -3π / 4 | `NaN` |
| 0 | 0 | 0 | `NaN` |
| 0 | -0 | -0 | `NaN` |
| < 0 (including `-0`) | 0 | π | 0 |
| < 0 (including `-0`) | -0 | -π | 0 |
| `-Infinity` | > 0 | π | -0 |
| -0 | > 0 | π / 2 | -π / 2 |
| `-Infinity` | < 0 | -π | 0 |
| -0 | < 0 | -π / 2 | π / 2 |

In addition, for points in the second and third quadrants (`x < 0`), `Math.atan2()` would output an angle less than

-

π
2

-\frac{\pi}{2}

 or greater than

π
2

\frac{\pi}{2}

.

Because `atan2()` is a static method of `Math`, you always use it as `Math.atan2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.atan2()

```js
Math.atan2(90, 15); // 1.4056476493802699
Math.atan2(15, 90); // 0.16514867741462683
```

### Difference between Math.atan2(y, x) and Math.atan(y / x)

The following script prints all inputs that produce a difference between `Math.atan2(y, x)` and `Math.atan(y / x)`.

```js
const formattedNumbers = new Map([
  [-Math.PI, "-π"],
  [(-3 \* Math.PI) / 4, "-3π/4"],
  [-Math.PI / 2, "-π/2"],
  [-Math.PI / 4, "-π/4"],
  [Math.PI / 4, "π/4"],
  [Math.PI / 2, "π/2"],
  [(3 \* Math.PI) / 4, "3π/4"],
  [Math.PI, "π"],
  [-Infinity, "-∞"],
  [Infinity, "∞"],
]);

function format(template, ...args) {
  return String.raw(
    { raw: template },
    ...args.map((num) =>
      (Object.is(num, -0)
        ? "-0"
        : formattedNumbers.get(num) ?? String(num)
      ).padEnd(5),
    ),
  );
}

console.log(`| x | y | atan2 | atan |
|-------|-------|-------|-------|`);

for (const x of [-Infinity, -1, -0, 0, 1, Infinity]) {
  for (const y of [-Infinity, -1, -0, 0, 1, Infinity]) {
    const atan2 = Math.atan2(y, x);
    const atan = Math.atan(y / x);
    if (!Object.is(atan2, atan)) {
      console.log(format`| ${x} | ${y} | ${atan2} | ${atan} |`);
    }
  }
}
```

The output is:
```

| x     | y     | atan2 | atan  |
|-------|-------|-------|-------|
| -∞    | -∞    | -3π/4 | NaN   |
| -∞    | -1    | -π    | 0     |
| -∞    | -0    | -π    | 0     |
| -∞    | 0     | π     | -0    |
| -∞    | 1     | π     | -0    |
| -∞    | ∞     | 3π/4  | NaN   |
| -1    | -∞    | -π/2  | π/2   |
| -1    | -1    | -3π/4 | π/4   |
| -1    | -0    | -π    | 0     |
| -1    | 0     | π     | -0    |
| -1    | 1     | 3π/4  | -π/4  |
| -1    | ∞     | π/2   | -π/2  |
| -0    | -∞    | -π/2  | π/2   |
| -0    | -1    | -π/2  | π/2   |
| -0    | -0    | -π    | NaN   |
| -0    | 0     | π     | NaN   |
| -0    | 1     | π/2   | -π/2  |
| -0    | ∞     | π/2   | -π/2  |
| 0     | -0    | -0    | NaN   |
| 0     | 0     | 0     | NaN   |
| ∞     | -∞    | -π/4  | NaN   |
| ∞     | ∞     | π/4   | NaN   |
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.atan2 |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.acos()`
* `Math.asin()`
* `Math.atan()`
* `Math.cos()`
* `Math.sin()`
* `Math.tan()`


Math.log2() - JavaScript

Math.log2()
===========

The **`Math.log2()`** static method returns the base 2 logarithm of a number. That is

∀
x
>
0
,

𝙼𝚊𝚝𝚑.𝚕𝚘𝚐𝟸
(
𝚡
)

=

log
2

(
x
)
=
the unique
y
 such that

2
y

=
x

\forall x > 0,;\mathtt{\operatorname{Math.log2}(x)} = \log\_2(x) = \text{the unique } y \text{ such that } 2^y = x

Try it
------

Syntax
------

```js
Math.log2(x)
```

### Parameters

`x`

A number greater than or equal to 0.

### Return value

The base 2 logarithm of `x`. If `x < 0`, returns `NaN`.

Description
-----------

Because `log2()` is a static method of `Math`, you always use it as `Math.log2()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

This function is the equivalent of `Math.log(x) / Math.log(2)`. For `log2(e)`, use the constant `Math.LOG2E`, which is 1 / `Math.LN2`.

Examples
--------

### Using Math.log2()

```js
Math.log2(-2); // NaN
Math.log2(-0); // -Infinity
Math.log2(0); // -Infinity
Math.log2(1); // 0
Math.log2(2); // 1
Math.log2(3); // 1.584962500721156
Math.log2(1024); // 10
Math.log2(Infinity); // Infinity
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.log2 |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Math.log2` in `core-js`
* `Math.exp()`
* `Math.log()`
* `Math.log10()`
* `Math.log1p()`
* `Math.pow()`


Math.clz32() - JavaScript

Math.clz32()
============

The **`Math.clz32()`** static method returns the number of leading zero bits in the 32-bit binary representation of a number.

Try it
------

Syntax
------

```js
Math.clz32(x)
```

### Parameters

`x`

A number.

### Return value

The number of leading zero bits in the 32-bit binary representation of `x`.

Description
-----------

`clz32` is short for **C**ount**L**eading**Z**eros**32**.

If `x` is not a number, it will be converted to a number first, then converted to a 32-bit unsigned integer.

If the converted 32-bit unsigned integer is `0`, `32` is returned, because all bits are `0`. If the most significant bit is `1` (i.e. the number is greater than or equal to 231), `0` is returned.

This function is particularly useful for systems that compile to JS, like Emscripten.

Examples
--------

### Using Math.clz32()

```js
Math.clz32(1); // 31
Math.clz32(1000); // 22
Math.clz32(); // 32

const stuff = [
  NaN,
  Infinity,
  -Infinity,
  0,
  -0,
  false,
  null,
  undefined,
  "foo",
  {},
  [],
];
stuff.every((n) => Math.clz32(n) === 32); // true

Math.clz32(true); // 31
Math.clz32(3.5); // 30
```

### Implementing Count Leading Ones and beyond

At present, there is no `Math.clon` for "Count Leading Ones" (named "clon", not "clo", because "clo" and "clz" are too similar especially for non-English-speaking people). However, a `clon` function can easily be created by inverting the bits of a number and passing the result to `Math.clz32`. Doing this will work because the inverse of 1 is 0 and vice versa. Thus, inverting the bits will inverse the measured quantity of 0's (from `Math.clz32`), thereby making `Math.clz32` count the number of ones instead of counting the number of zeros.

Consider the following 32-bit word:

```js
const a = 32776; // 00000000000000001000000000001000 (16 leading zeros)
Math.clz32(a); // 16

const b = ~32776; // 11111111111111110111111111110111 (32776 inverted, 0 leading zeros)
Math.clz32(b); // 0 (this is equal to how many leading one's there are in a)
```

Using this logic, a `clon` function can be created as follows:

```js
const clz = Math.clz32;

function clon(integer) {
  return clz(~integer);
}
```

Further, this technique could be extended to create a jumpless "Count Trailing Zeros" function, as seen below. The `ctrz` function takes a bitwise AND of the integer with its two's complement. By how two's complement works, all trailing zeros will be converted to ones, and then when adding 1, it would be carried over until the first `0` (which was originally a `1`) is reached. All bits higher than this one stay the same and are inverses of the original integer's bits. Therefore, when doing bitwise AND with the original integer, all higher bits become `0`, which can be counted with `clz`. The number of trailing zeros, plus the first `1` bit, plus the leading bits that were counted by `clz`, total to 32.

```js
function ctrz(integer) {
  integer >>>= 0; // coerce to Uint32
  if (integer === 0) {
    // skipping this step would make it return -1
    return 32;
  }
  integer &= -integer; // equivalent to `int = int & (~int + 1)`
  return 31 - clz(integer);
}
```

Then we can define a "Count Trailing Ones" function like so:

```js
function ctron(integer) {
  return ctrz(~integer);
}
```

These helper functions can be made into an asm.js module for a potential performance improvement.

```js
const countTrailsMethods = (function (stdlib, foreign, heap) {
  "use asm";
  const clz = stdlib.Math.clz32;

  // count trailing zeros
  function ctrz(integer) {
    integer = integer | 0; // coerce to an integer
    if ((integer | 0) == 0) {
      // skipping this step would make it return -1
      return 32;
    }
    // Note: asm.js doesn't have compound assignment operators such as &=
    integer = integer & -integer; // equivalent to `int = int & (~int + 1)`
    return (31 - clz(integer)) | 0;
  }

  // count trailing ones
  function ctron(integer) {
    integer = integer | 0; // coerce to an integer
    return ctrz(~integer) | 0;
  }

  // asm.js demands plain objects:
  return { ctrz: ctrz, ctron: ctron };
})(window, null, null);

const { ctrz, ctron } = countTrailsMethods;
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.clz32 |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Math.clz32` in `core-js`
* `Math`
* `Math.imul`


Math.tan() - JavaScript

Math.tan()
==========

The **`Math.tan()`** static method returns the tangent of a number in radians.

Try it
------

Syntax
------

```js
Math.tan(x)
```

### Parameters

`x`

A number representing an angle in radians.

### Return value

The tangent of `x`. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`.

**Note:** Due to floating point precision, it's not possible to obtain the exact value π/2, so the result is always finite if not `NaN`.

Description
-----------

Because `tan()` is a static method of `Math`, you always use it as `Math.tan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.tan()

```js
Math.tan(-Infinity); // NaN
Math.tan(-0); // -0
Math.tan(0); // 0
Math.tan(1); // 1.5574077246549023
Math.tan(Math.PI / 4); // 0.9999999999999999 (Floating point error)
Math.tan(Infinity); // NaN
```

### Math.tan() and π/2

It's not possible to calculate `tan(π/2)` exactly.

```js
Math.tan(Math.PI / 2); // 16331239353195370
Math.tan(Math.PI / 2 + Number.EPSILON); // -6218431163823738
```

### Using Math.tan() with a degree value

Because the `Math.tan()` function accepts radians, but it is often easier to work with degrees, the following function accepts a value in degrees, converts it to radians and returns the tangent.

```js
function getTanDeg(deg) {
  const rad = (deg \* Math.PI) / 180;
  return Math.tan(rad);
}
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.tan |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.acos()`
* `Math.asin()`
* `Math.atan()`
* `Math.atan2()`
* `Math.cos()`
* `Math.sin()`


Math.fround() - JavaScript

Math.fround()
=============

The **`Math.fround()`** static method returns the nearest 32-bit single precision float representation of a number.

Try it
------

Syntax
------

```js
Math.fround(doubleFloat)
```

### Parameters

`doubleFloat`

A number.

### Return value

The nearest 32-bit single precision float representation of `x`.

Description
-----------

JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a `Float32Array`. This can create confusion: checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical.

To solve this, `Math.fround()` can be used to cast the 64-bit float to a 32-bit float. Internally, JavaScript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to `0`. If the number is outside the range of a 32-bit float, `Infinity` or `-Infinity` is returned.

Because `fround()` is a static method of `Math`, you always use it as `Math.fround()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.fround()

The number 1.5 can be precisely represented in the binary numeral system, and is identical in 32-bit and 64-bit:

```js
Math.fround(1.5); // 1.5
Math.fround(1.5) === 1.5; // true
```

However, the number 1.337 cannot be precisely represented in the binary numeral system, so it differs in 32-bit and 64-bit:

```js
Math.fround(1.337); // 1.3370000123977661
Math.fround(1.337) === 1.337; // false
```

2
150

2^150

 is too big for a 32-bit float, so `Infinity` is returned:

```js
2 \*\* 150; // 1.42724769270596e+45
Math.fround(2 \*\* 150); // Infinity
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.fround |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Math.fround` in `core-js`
* `Math.round()`


Math.imul() - JavaScript

Math.imul()
===========

The **`Math.imul()`** static method returns the result of the C-like 32-bit multiplication of the two parameters.

Try it
------

Syntax
------

```js
Math.imul(a, b)
```

### Parameters

`a`

First number.

`b`

Second number.

### Return value

The result of the C-like 32-bit multiplication of the given arguments.

Description
-----------

`Math.imul()` allows for 32-bit integer multiplication with C-like semantics. This feature is useful for projects like Emscripten.

Because `imul()` is a static method of `Math`, you always use it as `Math.imul()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

If you use normal JavaScript floating point numbers in `imul()`, you will experience a degrade in performance. This is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point. However, with asm.js, which allows JIT-optimizers to more confidently use integers in JavaScript, multiplying two numbers stored internally as integers (which is only possible with asm.js) with `imul()` could be potentially more performant.

Examples
--------

### Using Math.imul()

```js
Math.imul(2, 4); // 8
Math.imul(-1, 8); // -8
Math.imul(-2, -2); // 4
Math.imul(0xffffffff, 5); // -5
Math.imul(0xfffffffe, 5); // -10
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.imul |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Math.imul` in `core-js`
* Emscripten on Wikipedia


Math.E - JavaScript

Math.E
======

The **`Math.E`** static data property represents Euler's number, the base of natural logarithms, e, which is approximately 2.718.

Try it
------

Value
-----

𝙼𝚊𝚝𝚑.𝙴
=
e
≈
2.718

\mathtt{\mi{Math.E}} = e \approx 2.718

| Property attributes of `Math.E` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

Description
-----------

Because `E` is a static property of `Math`, you always use it as `Math.E`, rather than as a property of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.E

The following function returns e:

```js
function getNapier() {
  return Math.E;
}

getNapier(); // 2.718281828459045
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.e |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.exp()`
* `Math.log()`
* `Math.log1p()`


Math.asin() - JavaScript

Math.asin()
===========

The **`Math.asin()`** static method returns the inverse sine (in radians) of a number. That is,

∀
x
∊
[

−
1

,
1
]
,

𝙼𝚊𝚝𝚑.𝚊𝚜𝚒𝚗
(
𝚡
)

=
arcsin
(
x
)
=
the unique
y
∊

[

−

π
2

,

π
2

]

 such that
sin
(
y
)
=
x

\forall x \in [{-1}, 1],;\mathtt{\operatorname{Math.asin}(x)} = \arcsin(x) = \text{the unique } y \in \left[-\frac{\pi}{2}, \frac{\pi}{2}\right] \text{ such that } \sin(y) = x

Try it
------

Syntax
------

```js
Math.asin(x)
```

### Parameters

`x`

A number between -1 and 1, inclusive, representing the angle's sine value.

### Return value

The inverse sine (angle in radians between

-

π
2

-\frac{\pi}{2}

 and

π
2

\frac{\pi}{2}

, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`.

Description
-----------

Because `asin()` is a static method of `Math`, you always use it as `Math.asin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.asin()

```js
Math.asin(-2); // NaN
Math.asin(-1); // -1.5707963267948966 (-π/2)
Math.asin(-0); // -0
Math.asin(0); // 0
Math.asin(0.5); // 0.5235987755982989 (π/6)
Math.asin(1); // 1.5707963267948966 (π/2)
Math.asin(2); // NaN
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.asin |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.acos()`
* `Math.atan()`
* `Math.atan2()`
* `Math.cos()`
* `Math.sin()`
* `Math.tan()`


Math.pow() - JavaScript

Math.pow()
==========

The **`Math.pow()`** static method returns the value of a base raised to a power. That is

𝙼𝚊𝚝𝚑.𝚙𝚘𝚠
(
𝚡
,
𝚢
)

=

x
y

\mathtt{\operatorname{Math.pow}(x, y)} = x^y

Try it
------

Syntax
------

```js
Math.pow(base, exponent)
```

### Parameters

`base`

The base number.

`exponent`

The exponent number.

### Return value

A number representing `base` taken to the power of `exponent`. Returns `NaN` in one of the following cases:

* `exponent` is `NaN`.
* `base` is `NaN` and `exponent` is not `0`.
* `base` is ±1 and `exponent` is ±`Infinity`.
* `base < 0` and `exponent` is not an integer.
Description
-----------

`Math.pow()` is equivalent to the `**` operator, except `Math.pow()` only accepts numbers.

`Math.pow(NaN, 0)` (and the equivalent `NaN ** 0`) is the only case where `NaN` doesn't propagate through mathematical operations — it returns `1` despite the operand being `NaN`. In addition, the behavior where `base` is 1 and `exponent` is non-finite (±Infinity or `NaN`) is different from IEEE 754, which specifies that the result should be 1, whereas JavaScript returns `NaN` to preserve backward compatibility with its original behavior.

Because `pow()` is a static method of `Math`, use it as `Math.pow()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.pow()

```js
// Simple cases
Math.pow(7, 2); // 49
Math.pow(7, 3); // 343
Math.pow(2, 10); // 1024

// Fractional exponents
Math.pow(4, 0.5); // 2 (square root of 4)
Math.pow(8, 1 / 3); // 2 (cube root of 8)
Math.pow(2, 0.5); // 1.4142135623730951 (square root of 2)
Math.pow(2, 1 / 3); // 1.2599210498948732 (cube root of 2)

// Signed exponents
Math.pow(7, -2); // 0.02040816326530612 (1/49)
Math.pow(8, -1 / 3); // 0.5

// Signed bases
Math.pow(-7, 2); // 49 (squares are positive)
Math.pow(-7, 3); // -343 (cubes can be negative)
Math.pow(-7, 0.5); // NaN (negative numbers don't have a real square root)
// Due to "even" and "odd" roots laying close to each other,
// and limits in the floating number precision,
// negative bases with fractional exponents always return NaN,
// even when the mathematical result is real
Math.pow(-7, 1 / 3); // NaN

// Zero and infinity
Math.pow(0, 0); // 1 (anything \*\* ±0 is 1)
Math.pow(Infinity, 0.1); // Infinity (positive exponent)
Math.pow(Infinity, -1); // 0 (negative exponent)
Math.pow(-Infinity, 1); // -Infinity (positive odd integer exponent)
Math.pow(-Infinity, 1.5); // Infinity (positive exponent)
Math.pow(-Infinity, -1); // -0 (negative odd integer exponent)
Math.pow(-Infinity, -1.5); // 0 (negative exponent)
Math.pow(0, 1); // 0 (positive exponent)
Math.pow(0, -1); // Infinity (negative exponent)
Math.pow(-0, 1); // -0 (positive odd integer exponent)
Math.pow(-0, 1.5); // 0 (positive exponent)
Math.pow(-0, -1); // -Infinity (negative odd integer exponent)
Math.pow(-0, -1.5); // Infinity (negative exponent)
Math.pow(0.9, Infinity); // 0
Math.pow(1, Infinity); // NaN
Math.pow(1.1, Infinity); // Infinity
Math.pow(0.9, -Infinity); // Infinity
Math.pow(1, -Infinity); // NaN
Math.pow(1.1, -Infinity); // 0

// NaN: only Math.pow(NaN, 0) does not result in NaN
Math.pow(NaN, 0); // 1
Math.pow(NaN, 1); // NaN
Math.pow(1, NaN); // NaN
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.pow |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.cbrt()`
* `Math.exp()`
* `Math.log()`
* `Math.sqrt()`
* Exponentiation (`**`)


Math.cosh() - JavaScript

Math.cosh()
===========

The **`Math.cosh()`** static method returns the hyperbolic cosine of a number. That is,

𝙼𝚊𝚝𝚑.𝚌𝚘𝚜𝚑
(
𝚡
)

=
cosh
(
x
)
=

e
x

+

e

−
x

2

\mathtt{\operatorname{Math.cosh}(x)} = \cosh(x) = \frac{\mathrm{e}^x + \mathrm{e}^{-x}}{2}

Try it
------

Syntax
------

```js
Math.cosh(x)
```

### Parameters

`x`

A number.

### Return value

The hyperbolic cosine of `x`.

Description
-----------

Because `cosh()` is a static method of `Math`, you always use it as `Math.cosh()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.cosh()

```js
Math.cosh(-Infinity); // Infinity
Math.cosh(-1); // 1.5430806348152437
Math.cosh(-0); // 1
Math.cosh(0); // 1
Math.cosh(1); // 1.5430806348152437
Math.cosh(Infinity); // Infinity
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.cosh |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Math.cosh` in `core-js`
* `Math.acosh()`
* `Math.asinh()`
* `Math.atanh()`
* `Math.sinh()`
* `Math.tanh()`


Math.atan() - JavaScript

Math.atan()
===========

The **`Math.atan()`** static method returns the inverse tangent (in radians) of a number, that is

𝙼𝚊𝚝𝚑.𝚊𝚝𝚊𝚗
(
𝚡
)

=
arctan
(
x
)
=
the unique
y
∊

[

−

π
2

,

π
2

]

 such that
tan
(
y
)
=
x

\mathtt{\operatorname{Math.atan}(x)} = \arctan(x) = \text{the unique } y \in \left[-\frac{\pi}{2}, \frac{\pi}{2}\right] \text{ such that } \tan(y) = x

Try it
------

Syntax
------

```js
Math.atan(x)
```

### Parameters

`x`

A number.

### Return value

The inverse tangent (angle in radians between

-

π
2

-\frac{\pi}{2}

 and

π
2

\frac{\pi}{2}

, inclusive) of `x`. If `x` is `Infinity`, it returns

π
2

\frac{\pi}{2}

. If `x` is `-Infinity`, it returns

-

π
2

-\frac{\pi}{2}

.

Description
-----------

Because `atan()` is a static method of `Math`, you always use it as `Math.atan()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.atan()

```js
Math.atan(-Infinity); // -1.5707963267948966 (-π/2)
Math.atan(-0); // -0
Math.atan(0); // 0
Math.atan(1); // 0.7853981633974483 (π/4)
Math.atan(Infinity); // 1.5707963267948966 (π/2)

// The angle that the line (0,0) -- (x,y) forms with the x-axis in a Cartesian coordinate system
const theta = (x, y) => Math.atan(y / x);
```

Note that you may want to avoid the `theta` function and use `Math.atan2()` instead, which has a wider range (between -π and π) and avoids outputting `NaN` for cases such as when `x` is `0`.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.atan |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.acos()`
* `Math.asin()`
* `Math.atan2()`
* `Math.cos()`
* `Math.sin()`
* `Math.tan()`


Math.log() - JavaScript

Math.log()
==========

The **`Math.log()`** static method returns the natural logarithm (base e) of a number. That is

∀
x
>
0
,

𝙼𝚊𝚝𝚑.𝚕𝚘𝚐
(
𝚡
)

=
ln
(
x
)
=
the unique
y
 such that

e
y

=
x

\forall x > 0,;\mathtt{\operatorname{Math.log}(x)} = \ln(x) = \text{the unique } y \text{ such that } e^y = x

Try it
------

Syntax
------

```js
Math.log(x)
```

### Parameters

`x`

A number greater than or equal to 0.

### Return value

The natural logarithm (base e) of `x`. If `x` is ±0, returns `-Infinity`. If `x < 0`, returns `NaN`.

Description
-----------

Because `log()` is a static method of `Math`, you always use it as `Math.log()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

If you need the natural log of 2 or 10, use the constants `Math.LN2` or `Math.LN10`. If you need a logarithm to base 2 or 10, use `Math.log2()` or `Math.log10()`. If you need a logarithm to other bases, use `Math.log(x) / Math.log(otherBase)` as in the example below; you might want to precalculate `1 / Math.log(otherBase)` since multiplication in `Math.log(x) * constant` is much faster.

Beware that positive numbers very close to 1 can suffer from loss of precision and make its natural logarithm less accurate. In this case, you may want to use `Math.log1p` instead.

Examples
--------

### Using Math.log()

```js
Math.log(-1); // NaN
Math.log(-0); // -Infinity
Math.log(0); // -Infinity
Math.log(1); // 0
Math.log(10); // 2.302585092994046
Math.log(Infinity); // Infinity
```

### Using Math.log() with a different base

The following function returns the logarithm of `y` with base `x` (i.e.

log
x

y

\log\_x y

):

```js
function getBaseLog(x, y) {
  return Math.log(y) / Math.log(x);
}
```

If you run `getBaseLog(10, 1000)`, it returns `2.9999999999999996` due to floating-point rounding, but still very close to the actual answer of 3.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.log |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.exp()`
* `Math.log1p()`
* `Math.log10()`
* `Math.log2()`
* `Math.pow()`


Math.sin() - JavaScript

Math.sin()
==========

The **`Math.sin()`** static method returns the sine of a number in radians.

Try it
------

Syntax
------

```js
Math.sin(x)
```

### Parameters

`x`

A number representing an angle in radians.

### Return value

The sine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`.

Description
-----------

Because `sin()` is a static method of `Math`, you always use it as `Math.sin()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.sin()

```js
Math.sin(-Infinity); // NaN
Math.sin(-0); // -0
Math.sin(0); // 0
Math.sin(1); // 0.8414709848078965
Math.sin(Math.PI / 2); // 1
Math.sin(Infinity); // NaN
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.sin |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.acos()`
* `Math.asin()`
* `Math.atan()`
* `Math.atan2()`
* `Math.cos()`
* `Math.tan()`


Math.sqrt() - JavaScript

Math.sqrt()
===========

The **`Math.sqrt()`** static method returns the square root of a number. That is

∀
x
≥
0
,

𝙼𝚊𝚝𝚑.𝚜𝚚𝚛𝚝
(
𝚡
)

=

x

=
the unique
y
≥
0
 such that

y
2

=
x

\forall x \geq 0,;\mathtt{\operatorname{Math.sqrt}(x)} = \sqrt{x} = \text{the unique } y \geq 0 \text{ such that } y^2 = x

Try it
------

Syntax
------

```js
Math.sqrt(x)
```

### Parameters

`x`

A number greater than or equal to 0.

### Return value

The square root of `x`, a nonnegative number. If `x < 0`, returns `NaN`.

Description
-----------

Because `sqrt()` is a static method of `Math`, you always use it as `Math.sqrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.sqrt()

```js
Math.sqrt(-1); // NaN
Math.sqrt(-0); // -0
Math.sqrt(0); // 0
Math.sqrt(1); // 1
Math.sqrt(2); // 1.414213562373095
Math.sqrt(9); // 3
Math.sqrt(Infinity); // Infinity
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.sqrt |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.cbrt()`
* `Math.exp()`
* `Math.log()`
* `Math.pow()`


Math.LOG2E - JavaScript

Math.LOG2E
==========

The **`Math.LOG2E`** static data property represents the base 2 logarithm of e, approximately 1.442.

Try it
------

Value
-----

𝙼𝚊𝚝𝚑.𝙻𝙾𝙶𝟸𝙴
=

log
2

(
e
)
≈
1.442

\mathtt{\mi{Math.LOG2E}} = \log\_2(\mathrm{e}) \approx 1.442

| Property attributes of `Math.LOG2E` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

Description
-----------

Because `LOG2E` is a static property of `Math`, you always use it as `Math.LOG2E`, rather than as a property of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.LOG2E

The following function returns the base 2 logarithm of e:

```js
function getLog2e() {
  return Math.LOG2E;
}

getLog2e(); // 1.4426950408889634
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.log2e |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.exp()`
* `Math.log()`
* `Math.log2()`


Math.LOG10E - JavaScript

Math.LOG10E
===========

The **`Math.LOG10E`** static data property represents the base 10 logarithm of e, approximately 0.434.

Try it
------

Value
-----

𝙼𝚊𝚝𝚑.𝙻𝙾𝙶𝟷𝟶𝙴
=

log
10

(
e
)
≈
0.434

\mathtt{\mi{Math.LOG10E}} = \log\_{10}(\mathrm{e}) \approx 0.434

| Property attributes of `Math.LOG10E` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

Description
-----------

Because `LOG10E` is a static property of `Math`, you always use it as `Math.LOG10E`, rather than as a property of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.LOG10E

The following function returns the base 10 logarithm of e:

```js
function getLog10e() {
  return Math.LOG10E;
}

getLog10e(); // 0.4342944819032518
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.log10e |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.exp()`
* `Math.log()`
* `Math.log10()`


Math.round() - JavaScript

Math.round()
============

The **`Math.round()`** static method returns the value of a number rounded to the nearest integer.

Try it
------

Syntax
------

```js
Math.round(x)
```

### Parameters

`x`

A number.

### Return value

The value of `x` rounded to the nearest integer.

Description
-----------

If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞.

**Note:** This differs from many languages' `round()` functions, which often round half-increments *away from zero*, giving a different result in the case of negative numbers with a fractional part of exactly 0.5.

`Math.round(x)` is not exactly the same as `Math.floor(x + 0.5)`. When `x` is -0, or -0.5 ≤ x < 0, `Math.round(x)` returns -0, while `Math.floor(x + 0.5)` returns 0. However, neglecting that difference and potential precision errors, `Math.round(x)` and `Math.floor(x + 0.5)` are generally equivalent.

Because `round()` is a static method of `Math`, you always use it as `Math.round()`, rather than as a method of a `Math` object you created (`Math` has no constructor).

Examples
--------

### Using round

```js
Math.round(-Infinity); // -Infinity
Math.round(-20.51); // -21
Math.round(-20.5); // -20
Math.round(-0.1); // -0
Math.round(0); // 0
Math.round(20.49); // 20
Math.round(20.5); // 21
Math.round(42); // 42
Math.round(Infinity); // Infinity
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.round |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Number.prototype.toPrecision()`
* `Number.prototype.toFixed()`
* `Math.abs()`
* `Math.ceil()`
* `Math.floor()`
* `Math.sign()`
* `Math.trunc()`


Math.abs() - JavaScript

Math.abs()
==========

The **`Math.abs()`** static method returns the absolute value of a number.

Try it
------

Syntax
------

```js
Math.abs(x)
```

### Parameters

`x`

A number.

### Return value

The absolute value of `x`. If `x` is negative (including `-0`), returns `-x`. Otherwise, returns `x`. The result is therefore always a positive number or `0`.

Description
-----------

Because `abs()` is a static method of `Math`, you always use it as `Math.abs()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.abs()

```js
Math.abs(-Infinity); // Infinity
Math.abs(-1); // 1
Math.abs(-0); // 0
Math.abs(0); // 0
Math.abs(1); // 1
Math.abs(Infinity); // Infinity
```

### Coercion of parameter

`Math.abs()` coerces its parameter to a number. Non-coercible values will become `NaN`, making `Math.abs()` also return `NaN`.

```js
Math.abs("-1"); // 1
Math.abs(-2); // 2
Math.abs(null); // 0
Math.abs(""); // 0
Math.abs([]); // 0
Math.abs([2]); // 2
Math.abs([1, 2]); // NaN
Math.abs({}); // NaN
Math.abs("string"); // NaN
Math.abs(); // NaN
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.abs |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.ceil()`
* `Math.floor()`
* `Math.round()`
* `Math.sign()`
* `Math.trunc()`


Math.cos() - JavaScript

Math.cos()
==========

The **`Math.cos()`** static method returns the cosine of a number in radians.

Try it
------

Syntax
------

```js
Math.cos(x)
```

### Parameters

`x`

A number representing an angle in radians.

### Return value

The cosine of `x`, between -1 and 1, inclusive. If `x` is `Infinity`, `-Infinity`, or `NaN`, returns `NaN`.

Description
-----------

Because `cos()` is a static method of `Math`, you always use it as `Math.cos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.cos()

```js
Math.cos(-Infinity); // NaN
Math.cos(-0); // 1
Math.cos(0); // 1
Math.cos(1); // 0.5403023058681398
Math.cos(Math.PI); // -1
Math.cos(2 \* Math.PI); // 1
Math.cos(Infinity); // NaN
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.cos |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.acos()`
* `Math.asin()`
* `Math.atan()`
* `Math.atan2()`
* `Math.sin()`
* `Math.tan()`


Math.SQRT1_2 - JavaScript

Math.SQRT1\_2
=============

The **`Math.SQRT1_2`** static data property represents the square root of 1/2, which is approximately 0.707.

Try it
------

Value
-----

𝙼𝚊𝚝𝚑.𝚂𝚀𝚁𝚃𝟷\_𝟸
=

1
2

≈
0.707

\mathtt{\mi{Math.SQRT1\_2}} = \sqrt{\frac{1}{2}} \approx 0.707

| Property attributes of `Math.SQRT1_2` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

Description
-----------

`Math.SQRT1_2` is a constant and a more performant equivalent to `Math.sqrt(0.5)`.

Because `SQRT1_2` is a static property of `Math`, you always use it as `Math.SQRT1_2`, rather than as a property of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.SQRT1\_2

The following function returns 1 over the square root of 2:

```js
function getRoot1\_2() {
  return Math.SQRT1\_2;
}

getRoot1\_2(); // 0.7071067811865476
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.sqrt1\_2 |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.pow()`
* `Math.sqrt()`


Math.cbrt() - JavaScript

Math.cbrt()
===========

The **`Math.cbrt()`** static method returns the cube root of a number. That is

𝙼𝚊𝚝𝚑.𝚌𝚋𝚛𝚝
(
𝚡
)

=

x
3

=
the unique
y
 such that

y
3

=
x

\mathtt{\operatorname{Math.cbrt}(x)} = \sqrt[3]{x} = \text{the unique } y \text{ such that } y^3 = x

Try it
------

Syntax
------

```js
Math.cbrt(x)
```

### Parameters

`x`

A number.

### Return value

The cube root of `x`.

Description
-----------

Because `cbrt()` is a static method of `Math`, you always use it as `Math.cbrt()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.cbrt()

```js
Math.cbrt(-Infinity); // -Infinity
Math.cbrt(-1); // -1
Math.cbrt(-0); // -0
Math.cbrt(0); // 0
Math.cbrt(1); // 1
Math.cbrt(2); // 1.2599210498948732
Math.cbrt(Infinity); // Infinity
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.cbrt |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Math.cbrt` in `core-js`
* `Math.pow()`
* `Math.sqrt()`


Math.max() - JavaScript

Math.max()
==========

The **`Math.max()`** static method returns the largest of the numbers given as input parameters, or -`Infinity` if there are no parameters.

Try it
------

Syntax
------

```js
Math.max()
Math.max(value1)
Math.max(value1, value2)
Math.max(value1, value2, /\* …, \*/ valueN)
```

### Parameters

`value1`, …, `valueN`

Zero or more numbers among which the largest value will be selected and returned.

### Return value

The largest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns -`Infinity` if no parameters are provided.

Description
-----------

Because `max()` is a static method of `Math`, you always use it as `Math.max()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

`Math.max.length` is 2, which weakly signals that it's designed to handle at least two parameters.

Examples
--------

### Using Math.max()

```js
Math.max(10, 20); // 20
Math.max(-10, -20); // -10
Math.max(-10, 20); // 20
```

### Getting the maximum element of an array

`Array.prototype.reduce()` can be used to find the maximum
 element in a numeric array, by comparing each value:

```js
const arr = [1, 2, 3];
const max = arr.reduce((a, b) => Math.max(a, b), -Infinity);
```

The following function uses `Function.prototype.apply()` to get the maximum of an array. `getMaxOfArray([1, 2, 3])` is equivalent to `Math.max(1, 2, 3)`, but you can use `getMaxOfArray()` on programmatically constructed arrays. This should only be used for arrays with relatively few elements.

```js
function getMaxOfArray(numArray) {
  return Math.max.apply(null, numArray);
}
```

The spread syntax is a shorter way of writing the `apply` solution to get the maximum of an array:

```js
const arr = [1, 2, 3];
const max = Math.max(...arr);
```

However, both spread (`...`) and `apply` will either fail or return the wrong result if the array has too many elements, because they try to pass the array elements as function parameters. See Using apply and built-in functions for more details. The `reduce` solution does not have this problem.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.max |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.min()`


Math.min() - JavaScript

Math.min()
==========

The **`Math.min()`** static method returns the smallest of the numbers given as input parameters, or `Infinity` if there are no parameters.

Try it
------

Syntax
------

```js
Math.min()
Math.min(value1)
Math.min(value1, value2)
Math.min(value1, value2, /\* …, \*/ valueN)
```

### Parameters

`value1`, …, `valueN`

Zero or more numbers among which the lowest value will be selected and returned.

### Return value

The smallest of the given numbers. Returns `NaN` if any of the parameters is or is converted into `NaN`. Returns `Infinity` if no parameters are provided.

Description
-----------

Because `min()` is a static method of `Math`, you always use it as `Math.min()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

`Math.min.length` is 2, which weakly signals that it's designed to handle at least two parameters.

Examples
--------

### Using Math.min()

This finds the min of `x` and `y` and assigns it to `z`:

```js
const x = 10;
const y = -20;
const z = Math.min(x, y); // -20
```

### Clipping a value with Math.min()

`Math.min()` is often used to clip a value so that it is always less than or
 equal to a boundary. For instance, this

```js
let x = f(foo);

if (x > boundary) {
  x = boundary;
}
```

may be written as this

```js
const x = Math.min(f(foo), boundary);
```

`Math.max()` can be used in a similar way to clip a value at the other end.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.min |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Math.max()`


Math.random() - JavaScript

Math.random()
=============

The **`Math.random()`** static method returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.

**Note:** `Math.random()` *does not* provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the `window.crypto.getRandomValues()` method.

Try it
------

Syntax
------

```js
Math.random()
```

### Parameters

None.

### Return value

A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).

Examples
--------

Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for `Math.random()` itself) aren't exact. If extremely large bounds are chosen (253 or higher), it's possible in *extremely* rare cases to reach the usually-excluded upper bound.

### Getting a random number between 0 (inclusive) and 1 (exclusive)

```js
function getRandom() {
  return Math.random();
}
```

### Getting a random number between two values

This example returns a random number between the specified values. The returned value is no lower than (and may possibly equal) `min`, and is less than (and not equal) `max`.

```js
function getRandomArbitrary(min, max) {
  return Math.random() \* (max - min) + min;
}
```

### Getting a random integer between two values

This example returns a random *integer* between the specified values. The value is no lower than `min` (or the next integer greater than `min` if `min` isn't an integer), and is less than (but not equal to) `max`.

```js
function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() \* (max - min) + min); // The maximum is exclusive and the minimum is inclusive
}
```

**Note:** It might be tempting to use `Math.round()` to accomplish that, but doing so would cause your random numbers to follow a non-uniform distribution, which may not be acceptable for your needs.

### Getting a random integer between two values, inclusive

While the `getRandomInt()` function above is inclusive at the minimum, it's exclusive at the maximum. What if you need the results to be inclusive at both the minimum and the maximum? The `getRandomIntInclusive()` function below accomplishes that.

```js
function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() \* (max - min + 1) + min); // The maximum is inclusive and the minimum is inclusive
}
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.random |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `window.crypto.getRandomValues()`