0

I came across a javascript program which was using !! operator for comparision. I know ! stands for NOT EQUAL. So logically !! means NOT OF NOT EQUAL which is EQUAL.

if (!!var_1){
   //...
}

My question is why do people sometimes use !! and not == operator ?

I've read similar questions, but couldn't figure out when exactly do we use this.

mrid
  • 5,408
  • 5
  • 19
  • 56
  • `So logically !! means NOT OF NOT EQUAL` ... no, it means NOT NOT ... basically coerces truthy values to `true` and falsey values to `false` – Jaromanda X Oct 18 '16 at 09:43
  • [Logical Not](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_NOT_(!)) – Tushar Oct 18 '16 at 09:44
  • !! converts the value to its Boolean representative – gurvinder372 Oct 18 '16 at 09:44
  • the first `!` inverts the `var_1` (false to true; vice versa). The second uses `!` inverts `!var_1` (false to true; vice versa). so if `var_1` is `true`, you would get `true`. and if `false`, you get `false`. It's an extra check for data validaty (I use it PHP) – Adam Azad Oct 18 '16 at 09:45
  • It does the same as `(var_1 == true)`, only with fewer characters. – Emil S. Jørgensen Oct 18 '16 at 09:46
  • people use !! to convert falsy / truthy values into a boolean value. a = null. !!a == false; – wayofthefuture Oct 18 '16 at 10:50

1 Answers1

2

!! is not an operator, it's just the ! operator twice.

!oObject  //Inverted boolean
!!oObject //Non inverted boolean so true boolean representation

Some output examples:

alert(true); // Gives true
alert(!true); // Gives false
alert(!!true); // Gives true
alert(!!!true); // Gives false

alert(false); // Gives false
alert(!false); // Gives true
alert(!!false); // Gives false
alert(!!!false); // Gives true

You see, one "!" just changes is from false to true or the other way around. With two or more of the "!", the process is simply repeating and changing its value again.

KoalaGangsta
  • 387
  • 1
  • 17
Anna Jeanine
  • 3,234
  • 8
  • 33
  • 58
  • I think you can add that many people simply use as shortcut for Boolean(), yet there are some differences in how it behaves with empty arrays – AntK Oct 18 '16 at 11:49