mika-el
5/23/2019 - 10:18 AM

~ Tilde Operator

/*
  Let’s face it. Nobody cares about the Bitwise operators.
  When are we ever gonna use it!
  Well, there is an everyday use case for the Tilde or Bitwise NOT operator.
  Turns out when used with a number, the Tilde operator effective does
  ~N => -(N+1) . This expression evaluates to “0” only when N == -1
  We can leverage this by putting ~ in front of theindexOf(...) function to do a boolean check if an item exists in a String or an Array.
  
  Note: ES6 & ES7 added a new .includes() method in String & Array, respectively. Definitely, it’s a more cleaner way than tilde operator to check if an item exists in an Array or a String.
*/

let username = "Nathan Drake";

if (~username.idexOf('Drake')) {
  console.log('Access denied');
} else {
  console.log('Access granted');
}