let a = !!12;
let b = !!'string';
let a = Boolean(12);
let b = Boolean('string');
let a = (12 == true);
let b = ('string' == true);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
!! | |
Boolean | |
Comparison |
Test name | Executions per second |
---|---|
!! | 194155328.0 Ops/sec |
Boolean | 152396816.0 Ops/sec |
Comparison | 43507520.0 Ops/sec |
I'd be happy to explain what's being tested in the provided benchmark.
Overview
The benchmark measures the performance of three different ways to convert values to booleans (true or false) in JavaScript:
!!
operatorBoolean()
function== true
)Options Compared
Here's a brief overview of each option being compared:
== true
) to convert values to booleans. It's not as straightforward as the other two options, but it works by checking if the value is equal to true
.Pros and Cons
Here are some pros and cons of each approach:
Boolean()
because it involves an additional operation (the bang operator).==
, including non-boolean values.Library Usage
None of the benchmark tests use external libraries.
Special JS Features or Syntax
None of the benchmark tests use special JavaScript features or syntax, such as async/await, generators, or decorators.
Other Alternatives
If you're interested in exploring alternative ways to convert values to booleans, here are a few examples:
Number()
and checking if the result is zero: let a = Number(12); let b = Number('string');
let a = /^[\d]+$/g.test('12'); let b = /^[\d]+$/.test('string');
Keep in mind that these alternatives may not be as readable or maintainable as the original options.
I hope this explanation helps!