0

Last night I was looking for an AngularJS snippet to manage a vertical tabs menu and I found this expression:

if(+!!variableName)
  doSomething();

Sorry, I can't understand what it mean +!!variableName How can I resolve this conditional expression?

Tushar
  • 78,625
  • 15
  • 134
  • 154
alessandro
  • 9,507
  • 5
  • 35
  • 46

3 Answers3

2

There is nothing cumbersome in that statement. It's just combination of two operators- Logical Not ! and Unary plus +.

Evaluation Steps:

  1. !!: Logical Not operator. Cast the variable to Boolean. See What is the !! (not not) operator in JavaScript?
  2. +: Unary plus. Cast to Number. See javascript: plus symbol before variable

In short, the result will be 1 if the variable is truthy and 0 if falsy.

Also note that there is no need of unary plus operator here as the Boolean itself is enough in the if().

The above statement can be safely changed to

if(!!variableName) // Note `+` is removed.
    doSomething();
Community
  • 1
  • 1
Tushar
  • 78,625
  • 15
  • 134
  • 154
2

This will be evaluated like,

say variableName is holding "test"

  1. !variableName => false
  2. !false => true
  3. +true => 1

This is how that expression will be evaluated.

! is a logical not operator, use for negating the values.

+ is normal arithmetic operator(aka unary plus as tushar mentioned), but if you make it preceded by any variable then it will try to convert that variable to a number. If it fails to do that, it will evaluate the expression to NaN

Rajaprabhu Aravindasamy
  • 63,064
  • 13
  • 90
  • 119
1

This is basically one way of saying that if the number if not null or undefined

if(+!!variableName)
  doSomething();

if variableName is 0, empty (""), null or undefined, it will translate to false or else to true.

For example, if

var variableName = null;

now, this will translate to (+!!null) -> (+!true) -> (+false) -> false

similarly, if

var variableName = "anything";

This will translate to (+!!"anything") -> (+!false) -> (+true) -> true

+ in this case has no effect on the outcome, so can be safely removed.

In fact, whole conditional expression can be replaced by

if(variableName)
  doSomething();
gurvinder372
  • 61,170
  • 7
  • 61
  • 75