1

I came across this line of code recently, and want to understand what it means and does, as my javascript-foo is not that hot :

if ((+!!config.template) + (+!!config.templateUrl) !== 1) {} 

from what I can gather, it is checking to see if either option is set (so either template, or templateUrl must be set, not both or none)

so, if config.template was set,

  • +config.template would not work (template is not a number)
  • !config.template would return false (-1)
  • !!config.template would return true (0)
  • +!!config.template would therefore return 1

if config.template was not set,

  • !config.template would return true (0)
  • !!config.template would return false (-1)
  • +!!config.template would therefore return 0

if then you were to apply the same to config.templateUrl , you would end up with 1 if set, 0 if not

So the final test is to see if the sum of config.template and config.templateUrl is 1 (ie one or the other is set)

Is this valid reasoning ?

3
  • 3
    Wow... this had me cry out in pain. Commented May 29, 2015 at 9:16
  • 4
    Almost right, except that +(true) === 1 and +(false) === 0 Commented May 29, 2015 at 9:16
  • Actually the above expression is the equivalent to if (!config.template === !config.templateUrl) {}. It looks much simpler that way. Commented May 29, 2015 at 9:24

1 Answer 1

3

The bool value is being cast to a Number by prepending it with +.

!! in the code above is checking for existence of the property template on config. If there is no template found !! would usually return false, however by prepending +, it returns 0. Both +!! statements return numbers, which when they're added together will either be 0 or 1.

The final check will return true if both or none were set / true (!== 1)

Sign up to request clarification or add additional context in comments.

5 Comments

@RoryGilchrist : why would the code fail if both were set ? Yes, the expression would be 2, but the test checks for !== 1 , therefore it would execute the code in {} (which was the intention of the author - a message saying "you must specify one or the other) or am I being thick ?
You're right, I misread. So basically in the code above, it's want's either none or both to be set, but not just one.
@RoryGilchrist exactly so: "which when they're added together will be 0, 1 or 2".
@Armfoot Other way round amigo, it would be false if it were 1, but not 2. 1 !== 1 is fasle because 1 == 1, but 2 !== 1 is true because 2 is not 1.
@RoryGilchrist yeah xD nevermind, I edited that... I was thinking === from the question's comment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.