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

Find out how to determine the minimum value in a list of bigint values

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

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

    let minValue = values.shift();

    for (const value of values) {
        if (value < minValue) {
            minValue = value;
        }
    }

    return minValue;
}

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

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

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(min(1000000n, 1024, 2124, 18014398509481982n, -394n)); // -394n
// ...

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

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

Hope you found this post useful. It was published . Please show your love and support by sharing this post.