TypeError: Cannot mix BigInt and other types, use explicit conversions (I was trying to add/mix BigInt with var)

Tags: , ,



I was trying to add large numbers using BigInt and add to sum.

var sum=0; 
    for(let i in ar){
        sum += BigInt(ar[i]);
    }
    return (sum);  

But got an error saying:

sum += BigInt(ar[i]);
               ^

TypeError: Cannot mix BigInt and other types, use explicit conversions

Answer

I tried and came up to answer that we can not mix BigInt to another types. So I converted integer sum into BigInt and then adding it to BigInt. as said in “https://javascript.info/bigint”:

alert(1n + 2); // Error: Cannot mix BigInt and other types

let bigint = 1n; let number = 2;

// number to bigint alert(bigint + BigInt(number)); // 3

// bigint to number alert(Number(bigint) + number); // 3 So my working solution now is:

var sum=0
for(let i in ar)
    sum = BigInt(sum) + BigInt(ar[i]);
return (sum);


Source: stackoverflow