JavaScript – Understanding the +!! Operator in an If Statement

javascript

I was reviewing the code for an angularjs factory to better understand how it works. The code contains an if statement that I don't fully understand.

In a plnkr demo the author wrote this:

if ((+!!config.template) + (+!!config.templateUrl) !== 1) {
  throw new Error('Expected modal to have exactly one of either `template` or `templateUrl`');
}

It is slightly different in the github repo:

if (!(!config.template ^ !config.templateUrl)) {
  throw new Error('Expected modal to have exactly one of either `template` or `templateUrl`');
}

Obviously by the error message it is checking to see if one of the two exists. I'm just not sure how it comes to the conclusion. I have not been able to find any information on ^ or +!

My question is: How does this if statement work? (^ or +! or +!! specifically)

Best Answer

!! converts a value to a boolean (true or false). + then converts that boolean to a number, either 1 for true or 0 for false.

> +true
1
> +false
0

Personally I find it clearer to write something like this, when dealing with two booleans:

if (!config.template == !config.templateUrl) {
  throw ...
}

Code clarity and readability be damned, apparently.