Reputation: 9295
In JavaScript, which is a more efficient way to cast a value to Boolean
type,
let booleanVal = !!valueToCast;
or
let booleanVal = Boolean(valueToCast);
PS I need to typecast in an array tof 1000 elements in api in some use case, so I was wondering which one had the least overhead
Upvotes: 2
Views: 762
Reputation: 7273
There's already a jsperf that measures the difference between the two at https://jsperf.com/bool-cast-vs-not which shows that in most browsers Boolean(value)
was significantly slower than !!value
(though, now in the newer Chrome 59+ it is slightly faster).
However, even at the slowest it was still over 30,000,000 operations a second making it pretty insignificant for your 1000 element dataset.
So choose whichever you like :)
Upvotes: 3