Girrafish
Girrafish

Reputation: 2482

JS - Is there a case where !!x and x don't represent the same logical value

I was refactoring my code and I fell on a few lines where I was using double negation in the if conditions.

It got me thinking, are there any cases in javascript where if (!!x) wont resolve to the same condition as if (x)?

Note: I'm not talking about !!x !== x, I mean do they represent different logical values. In other words, is there a situation where these 2 expressions won't have the same outcome.

x ? true : false;
!!x ? true : false;

Upvotes: 1

Views: 110

Answers (3)

Jquenel
Jquenel

Reputation: 99

As it was already answered, all values are falsy or truthy, so there is no variable x such as x != !!x.

However, if you x is not a variable, but is a logical unit such as (a || b), there exist cases where your yet to be evaluated x does not equal !!x.

From the MDN Javascript documentation :

o5 = 'Cat' || 'Dog'      // t || t returns "Cat"
o6 = false || 'Cat'      // f || t returns "Cat"

If you evaluate !('Cat' || 'Dog'), the return value would be false, then you get !!('Cat' || 'Dog') which will of course return true.

So yeah, in that case not only you can get x !== !!x ; you can also get x != !!x

Upvotes: 1

Sandro
Sandro

Reputation: 1061

No there isn't.

Every value in JS is either falsy or truthy:

  • almost all objects are truthy
  • all numbers expect 0 are truthy
  • all strings expect the empty string are truthy
  • 0 is falsy
  • empty string is falsy
  • undefined and null are falsy

!!expr will turn a falsy value to false and a truthy value to true. It is essentially a conversion of expr to a boolean.

Upvotes: 1

Wais Kamal
Wais Kamal

Reputation: 6180

In the case where x = NaN, !!x is not equal to x. Here is a test:

var x = NaN;
if(!!x == x) {
  console.log("!!x is equal to x");
} else if (!!x !== x) {
  console.log("!!x is not equal to x");
}

However, their logical value is the same, which means they will perform equally inside a logical test. Thus, irrespective of the nature of x, if(!!x) is the same as if(x), and hence every instance of if(!!x) can be safely replaced with if(x);

var x = NaN;
if(!!x) {
  console.log("True");
} else if(x) {
  console.log("False");
}

var x = NaN;
if(x) {
  console.log("True");
} else if(!!x) {
  console.log("False");
}

I made two snippets (one in which I swapped the tests) such that the if statement does not stop at the first test if it is valid.

Upvotes: 2

Related Questions