Muirik Muirik -4 years ago 81
Javascript Question

'!!' versus just checking for "truthy" or "falsy" existence

Re: the

!!
in JavaScript, from my understanding, this will cast an object to a boolean. According to an answer in another SO thread, it "coerces oObject to boolean. If it was falsey (e.g. 0, null, undefined, etc.), it will be false, otherwise, true."

My question therefore is, is this
!!
any more robust than simply checking for falsy or truthy existence? For instance, I could do something like this:

return !!(this.services[0] && this.services[0].service);


Or I could do this:

if (this.services[0] && this.services[0].service) {
return true;
} else {
return false;
}


Are these functionality equivalent?

Answer Source

&& returns the first falsy value, so !! may be better if you truly need the consistency a boolean.

An example would be if you are watching for changes to an expression (like in AngularJS):

$scope.$watch(() => val1 && val2, (newVal, oldVal) => { 
    //... 
});

If val1 starts out undefined, then val1 && val2 would evaluate to undefined. If val1 later becomes false, then val1 && val2 would evaluate to false. So your watcher would execute again when you may not want it to! So it may be better to watch !!(val1 && val2).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download