Question

In javascript I have seen the usage of

if (!!foo.bar) {
    doSomething();
}

What is the performance and other differences between this and

if (Boolean(foo.bar)) {
    doSomething();
}

?

Is there any overhead for the use of constructor typecasting over negation?

Another (better) example is:

doSomethingWithBoolean(!!foo.bar);
Was it helpful?

Solution 2

By calling Boolean(foo.bar) , you are getting a wrapped boolean object which would have some additional Object sspecific functionality (and here you dont want them)

Using !!foo.bar you'll get a boolean literal, So i think this evaluation will be fast.

OTHER TIPS

I dont think there will be any significant performance issue. !!foo.bar is doing same thing with less typing.

With boolean(foo.bar) there might be very-very small performance issue as this is using constructor but with today's hardware that is ignorable.

After all I will simply use foo.bar or !foo.bar

The double negation is just quicker to type and makes for shortened files. It’s a common compression technique.

It could be (a tiny little bit) slower, but since it’s an ubiquitous shortcut I guess there’s a compiler optimization. Don’t nitpick over such implementation details!

In Javascript, with

if (Boolean(foo.bar)) {
    doSomething();
}

doSomething will execute since Boolean() create a not null object, even if it is Boolean(false). "Boolean" returns an object, "!!" returns a boolean value, e.g. true/false. My source for telling this is here.

PS: Boolean, with a caps at the beginning, is the Javascript object

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top