The Math.imul() function returns the result of the C-like 32-bit multiplication of the two parameters.


Math.imul(a, b)


First number.
Second number.

Return value

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


Math.imul() allows for fast 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).


Using Math.imul()

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


For demonstrational purposes of how binary addition works, this can be emulated with the following function:

Math.imul = Math.imul || function(a, b) {
  var ah = (a >>> 16) & 0xffff;
  var al = a & 0xffff;
  var bh = (b >>> 16) & 0xffff;
  var bl = b & 0xffff;
  // the shift by 0 fixes the sign on the high part
  // the final |0 converts the unsigned value into a signed value
  return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0)|0);

However, the following function will be more efficient, especially if the browser is one that does not have integer optimizations because modern hardware rarely, if ever, can be beat.

Math.imul = Math.imul || (function()
  if (document.documentMode&&(document.documentMode!=0)&&(doument.documentMode<5)) {
    // For Internet Explorer version less than 5, where the Math library support is iffy
    return function(a, b) {
      // 2147483648 = 231 = the maximum value of a signed integer plus one
      var product = a*b, remainder = product%2147483648;
      return (product-remainder)/2147483648 + remainder;
  } else {
    // If the browser supports most of the Math library. Also, if the browser compiles the javascript then theres a good chance it will recognize the
    //  division and modulus of the same variable, and optimize the division and modulus into a single instruction.
    return function(a, b) {
      var product = a * b;
      return Math.floor(product/2147483648)+(product%2147483648);


Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Math.imul' in that specification.
Standard Initial definition.
ECMAScript 2017 Draft (ECMA-262)
The definition of 'Math.imul' in that specification.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 28 20 (20) ? 16 7
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? ? 20.0 (20) ? ? 7

Document Tags and Contributors

 Last updated by: Peppesterest,