3

I have encountered those operators that are checking for user.rank property:

<div ng-show="!!user.rank">
    {{user.rank}}
</div>
<button ng-show="!user.rank"  ng-click="addRank(user)">Add Rank</button>

How are they different and what can we use instead?

Hussein Salman
  • 6,562
  • 13
  • 53
  • 88

2 Answers2

14

A single bang (!) is used to negate a boolean.

Double bang (!!) is used to coerce a truthy/falsey value to a boolean true or false.

for example

var x = 0; // a falsey value
console.log(x); // logs 0
console.log(!x)// logs true
console.log(!!x)// logs false

var y = "Hello world"; // a truthy value
console.log(y); // logs "Hello world"
console.log(!y)// logs false
console.log(!!y)// logs true

Applied to your specific case

ng-show="!!user.rank"

ng-show is no doubt expecting an actual boolean, and user.rank is obviously either truthy or falsey - coercing it to a boolean satisfies your angular directive appropriately.

Jamiec
  • 118,012
  • 12
  • 125
  • 175
  • 1
    you can coerce a boolean to its invert value using !!! and to its normal value using !!!! and so on, hahahah –  Jun 07 '17 at 14:07
-1

What is the !! (not not) operator in JavaScript?

From the JS wiki on SO

Regarding !!:

"Coerces oObject to boolean. If it was falsey (e.g. 0, null, undefined, etc.), it will be false, otherwise, true."

"It converts a nonboolean to an inverted boolean (for instance, !5 would be false, since 5 is a non-false value in JS), then boolean-inverts that so you get the original value as a boolean (so !!5 would be true)"

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

EL_DANIMAL
  • 72
  • 1
  • 11