What's the Math.abs() Alternative for BigInt Values in JavaScript?

The JavaScript Math.abs() method only works on the number primitive values, and not on the bigint primitive values. Therefore, to determine the absolute value for bigint numbers, you can do the following:

// ES10+
const abs = (n) => (n < 0n) ? -n : n;

console.log(abs(-18014398509481982n)); // 18014398509481982n
console.log(abs(BigInt(-Number.MAX_SAFE_INTEGER))); // 9007199254740991n

console.log(abs(-10n)); // 10n
console.log(abs(-0n)); // 0n

The "n" at the end of a number merely suggests that the number is a bigint primitive.

This function works with numbers as well:

// ...
console.log(abs(-25)); // 25
console.log(abs(-Infinity)); // Infinity

The only caveat is that -0 number literal will return -0. If you must absolutely support this edge case, then you can use the following instead:

const abs = (n) => (n === -0 || n < 0n) ? -n : n;

console.log(abs(-0)); // 0

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.