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

The JavaScript Math.max() method only works on the number primitive values, and not on the bigint primitive values. Therefore, to find the maximum value in a list of bigint numbers, you can do the following:

function max(...values) {
    if (values.length < 1) {
        return -Infinity;
    }

    let maxValue = values.shift();

    for (const value of values) {
        if (value > maxValue) {
            maxValue = value;
        }
    }

    return maxValue;
}

You can use this function to find the maximum bigint value like so:

// ES10+
console.log(max(1000n, 400n, 754n, 394n)); // 1000n
console.log(max(18014398509481982n, 33314398509441982n, 44545434534212n)); // 33314398509441982n
console.log(max(-18014398509481982n, -33314398509441982n, 44545434534212n)); // 44545434534212n
// ...

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

With this function, you may mix numbers and bigints (because a number value and a bigint value can be compared as usual):

// ES10+
console.log(max(1000000n, 1024, 2124, 18014398509481982n, -394n)); // 18014398509481982n
// ...

You may also use this function to find the maximum value in a list of numbers:

console.log(max(456, 333, 231, -321, -110, 0, 44)); // 456
// ...

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.