Skip to content
Advertisement

Uncertainty with the !! operator (double negation)

I saw in a pull request that the double negation operator (!!) is used for the focus attribute of a text field as follows:

focused: !!value || value === 0,

As far as I know, the operator converts everything to a boolean. If it was falsy (for example 0, null, undefined,..), it will be false, otherwise, true.

In my case, i.e. if value = 0, the following comes out:

focused: false || true

The || operator here therefore makes no sense for the value 0 or am I completely confused?

Advertisement

Answer

It looks like a check for numbers to get false for '', "", false, NaN, undefined and null. Other bjects, like functions, arrays or simple objects returns true;

const check = value => !!value || value === 0;

console.log(check(0));
console.log(check(1));
console.log(check(''));
console.log(check(""));
console.log(check(false));
console.log(check(NaN));
console.log(check(null));
console.log(check(undefined));
console.log(check({}));
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement