0

I have come across code in a web app where it uses !!, I was told that this enforces a check for true or false instead of truthy or falsy. Is this correct?

if (!!this._currentItemIndex) {
      this._findItemByCurrentIndex();
}

I have been having trouble finding any resources online to explain this.

Graeme Muir
  • 31
  • 1
  • 5
  • Its correct. The use of !! (or "bang bang") just forces the value to the inverse true/false of what it's truthy value is, and then inverses it yet again to get the true/false version of the truthy value. – Taplar Jul 09 '20 at 22:26
  • That is correct, the `!!` will convert the value to a boolean, but the `if` statement would be equivalent to one that does not use `!!`. – CRice Jul 09 '20 at 22:26
  • does this helps you? https://stackoverflow.com/questions/784929/what-is-the-not-not-operator-in-javascript – Carlos1232 Jul 09 '20 at 22:26
  • 3
    Does this answer your question? [What is the !! (not not) operator in JavaScript?](https://stackoverflow.com/questions/784929/what-is-the-not-not-operator-in-javascript) – mcjmzn Jul 09 '20 at 22:26
  • It's a way of typecasting to boolean. if value of `this._currentItemIndex` is undefined adding `!!` will evaluate it to false. If the value of `this._currentItemIndex` is `0` it will evaluate to false. – Alfred Ayi-bonte Jul 09 '20 at 22:27
  • `!` negates the value, so if your `this._currentItemIndex` is true it will be false. If you use `!!` on a boolean it will always return the value since it negates it twice so: true => false => true or false => true => false. Mostly the `!!` is used to make sure you definetly have a boolean type. – Timon Jul 09 '20 at 22:29
  • A simple google search for "javascript double exclamation mark operator" returns quite a few articles, here are two of them: (https://medium.com/@edplatomail/js-double-bang-or-the-not-operator-part-40e55d089bf0), and (https://medium.com/better-programming/javascript-bang-bang-i-shot-you-down-use-of-double-bangs-in-javascript-7c9d94446054) – ISAE Jul 09 '20 at 22:30

1 Answers1

0

Normally you'll see code like:

let x = !!y;

Where this is casting whatever value y has into a simple true or false outcome, a boolean. This is often employed to avoid retaining references to things you don't need, like y could be a complex structure but you don't care about the details, you just want to track if it was assigned.

It's unusual to see this employed in an if since it really doesn't do anything useful. It converts to a boolean, but if will anyway. This is just junk code.

It might as well be if (!!!!!!!!!!!!!!!!!!!!x) for all the good it does.

A better version would look like:

if (this._currentItemIndex) {
  // Some non-zero value was assigned
}

Or if it is populated:

if (this._currentItemIndex > 0) {
  // Communicates intent better
}
tadman
  • 208,517
  • 23
  • 234
  • 262