Math.imul(a, b) multiplies two numbers as 32-bit integers and returns a signed 32-bit result. If the answer is too big, it wraps around instead of becoming a huge number.
Math is built into JavaScript. Call the method directly. It is not a constructor, so never write new Math().
Syntax
Call Math.imul() like this. Start with this line.
JavaScript
Math.imul(a, b)
Call
What it does
Math.imul(a, b)
Returns a * b as a signed 32-bit integer.
Built into JavaScript. Call Math.imul() on the Math object — no import required.
Library declarations
JavaScript
Math.imul(a, b)
JavaScript
interface Math {
imul(x: number, y: number): number;
}
Parameters
Parameter
Description
a
Required. The first number. It is converted to a 32-bit integer.
b
Required. The second number. It is converted to a 32-bit integer.
Return Value
Return Value
Description
number
The product as a signed 32-bit integer, from -2147483648 to 2147483647.
JavaScript Examples
Example 1 — Basic Use
For small numbers, Math.imul() gives the same answer as *.
Normal multiply.65536 * 65536 is 4294967296, a number bigger than 32 bits.
imul wraps. In 32 bits that value is 0.
Sign flip.2147483647 * 2 wraps into the negative range and becomes -2.
Example 3 — Simple String Hash
A classic hash multiplies by 31 for every character. Math.imul() keeps the number at 32 bits.
JavaScript
function hash(text) {
var h = 0;
for (var i = 0; i < text.length; i++) {
h = (Math.imul(31, h) + text.charCodeAt(i)) | 0;
}
return h;
}
console.log(hash("hello")); // 99162322
console.log(hash("Hello")); // 69609650