0

Can someone point me in the way towards some documentation as to what it means to use !!. I have a return statement

return !! _.reduce(collection, function(a, b){
  // a is a result of last call
  // b is result of calling iterator on current value
  console.log("a: "+a)
  console.log("b: "+b)
  console.log(iterator(b));
  //will return false or true based on test
     return a && iterator(b);
    }, true)
}

which works but this doesn't

return  _.reduce(collection, function(a, b){
  // a is a result of last call
  // b is result of calling iterator on current value
  console.log("a: "+a)
  console.log("b: "+b)
  console.log(iterator(b));
  //will return false or true based on test
     return a && iterator(b);
    }, true)
}
  • You can refer to this question: [https://stackoverflow.com/questions/784929/what-is-the-not-not-operator-in-javascript](https://stackoverflow.com/questions/784929/what-is-the-not-not-operator-in-javascript) – Naseh Badalov Apr 10 '20 at 21:28

1 Answers1

1

!! is shorthand in Javascript for converting any value to its boolean equivalent.

The way it works is that a single ! operator converts any value to its boolean opposite. A second ! then converts it back to its original boolean value, because the opposite of the opposite (in boolean terms) is always the original.

machineghost
  • 28,573
  • 26
  • 128
  • 197
  • But by this logic the second mentioned code should have worked. – Kunal Raut Apr 10 '20 at 21:32
  • You haven't provided all your code, so I don't know what `iterator` is. I also don't know what "worked" means. I answered the question about `!!` (although it's been answered before elsewhere), but if you need further help perhaps make a separate question, and include all the relevant details. But also, be careful about asking SO to "debug my code for me". If my explanation helped you understand `!!`, perhaps try debugging further on your own first, and try to save questions for "why/how does X work?" – machineghost Apr 10 '20 at 21:34
  • 1
    @KunalRaut incorrect. The first `!` performs a "convert to boolean" operation. Whatever is returned by the `_.reduce()`, the value after the first `!` will be either `true` or `false`. The second `!` applied to that result can therefore only be `true` or `false`. The plain result of `_.reduce` could be *anything*. – Pointy Apr 10 '20 at 21:42
  • @Pointy Ok i got it now thanks! – Kunal Raut Apr 10 '20 at 21:44