File size: 2,276 Bytes
780c9fe |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
---
title: Math.imul()
short-title: imul()
slug: Web/JavaScript/Reference/Global_Objects/Math/imul
page-type: javascript-static-method
browser-compat: javascript.builtins.Math.imul
sidebar: jsref
---
The **`Math.imul()`** static method returns the result of the C-like 32-bit multiplication of the two parameters.
{{InteractiveExample("JavaScript Demo: Math.imul()")}}
```js interactive-example
console.log(Math.imul(3, 4));
// Expected output: 12
console.log(Math.imul(-5, 12));
// Expected output: -60
console.log(Math.imul(0xffffffff, 5));
// Expected output: -5
console.log(Math.imul(0xfffffffe, 5));
// Expected output: -10
```
## Syntax
```js-nolint
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](https://en.wikipedia.org/wiki/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](/en-US/docs/Games/Tools/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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Math.imul` in `core-js`](https://github.com/zloirock/core-js#ecmascript-math)
- [es-shims polyfill of `Math.imul`](https://www.npmjs.com/package/math.imul)
- [Emscripten](https://en.wikipedia.org/wiki/Emscripten) on Wikipedia
|