var b = true;
b === true || b === false
typeof b === 'boolean'
!!b === b
Boolean(b) === b
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Check strict equal of possibilities | |
typeof | |
convert bool using double not | |
convert bool using Boolean |
Test name | Executions per second |
---|---|
Check strict equal of possibilities | 11686872.0 Ops/sec |
typeof | 12071184.0 Ops/sec |
convert bool using double not | 7527145.0 Ops/sec |
convert bool using Boolean | 3694200.0 Ops/sec |
The provided benchmark tests various methods of checking and converting boolean values in JavaScript, focusing on performance and determining which approach is more efficient. Here’s a breakdown of the individual test cases, their implications, pros/cons, and alternative considerations:
Check strict equal of possibilities (b === true || b === false
)
b
strictly equals either true
or false
.Typeof (typeof b === 'boolean'
)
typeof
operator to evaluate whether b
is of the boolean type.typeof
operator, which might have some overhead due to its operation, although typically negligible for primitive type checks.Convert bool using double not (!!b === b
)
!!
) converts a value to its boolean equivalent, and then it checks if it equals the original boolean b
.Convert bool using Boolean (Boolean(b) === b
)
Boolean
constructor to convert b
to a boolean and checks if it matches the original.Boolean
constructor.From the results, the typeof
method shows the highest execution speed, followed closely by the strict equality check. The double negation method is substantially slower, followed by the use of the Boolean
constructor. This hierarchy provides insights into which methods are most performant in JavaScript for checking boolean values.
if (b) { ... }
) to trigger branches based on truthiness. However, these might not be suitable for pure type checks.Overall, for a broad variety of use cases, the typeof
operator and strict equality checks are generally safest, while the idiomatic double negation can be employed for performance-sensitive contexts where brevity is valued.