Sorry if I\'ve made mistakes writing this post. I\'m new here and I don\'t know how this works, hope I learn quick. I am also new at JavaScript.
So the question is:
Because JavaScript has short circuit evaluation and your strings are truthy then you need to use the second approach or what you referred to as "the normal way".
The first way does not work because you end up evaluating the wrong thing. Evaluation works like this:
var result = 0 || "zero" ;
0
is evaluated and determined to be falsy. "zero"
is evaluated as truthy and becomes the result.var result = "zero" || 0 ;
"zero"
is evaluated and determined to be truthy and returned as the result. 0
is not evaluated because short circuit evaluation.In your original code:
if (codePrompt == (codeSwitch || codeSwitchBG || codeBlur || codeShowInfo)){};
The operator associativity of ||
is left to right. Parenthesis are evaluated inner to outer.
(codeSwitch || codeSwitchBG || codeBlur || codeShowInfo)
is evaluated first. Because of the rules we already discussed the result becomes codeSwitch
:
So you end up evaluating:
if(codePrompt == codeSwitch)
Which of course is wrong.