Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between !! and ! in JavaScript [duplicate]

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?

like image 529
Hussein Salman Avatar asked Dec 06 '25 08:12

Hussein Salman


1 Answers

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.

like image 50
Jamiec Avatar answered Dec 08 '25 22:12

Jamiec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!