The result of "HelloWorld" && "GoodbyeWorld"
is "GoodbyeWorld"
which is why you're getting the result you are, the previous way you were doing it is the simplest solution
Javascript how to use the and/or operator with parenthesis
-
29-06-2022 - |
Question
I have an object that contains a string HelloWorld
in the attribute hello
. I want to check for two strings, and if it does not match with either one, then I want to execute certain code.
var item = { hello: "HelloWorld" }
item.hello !== "HelloWorld" && item.hello !== "GoodbyeWorld" // false, correct
However, I feel this can be optimized and made more readable:
item.hello !== ("GoodbyeWorld" && "HelloWorld") // false, correct
item.hello !== ("HelloWorld" && "GoodbyeWorld") // true WTF?
I expected both checks to be falsy, but surely I'm missing something here. I think I do not have a correct understanding of the AND/OR operator in javascript, or I am using the parenthesis in a wrong manner. Can anyone explain?
La solution
Autres conseils
Let's take a look at this line
item.hello !== ("HelloWorld" && "GoodbyeWorld") // true WTF?
The logical AND operator evaluates its right operand, if lVal
is a truthy value.
Note, a truthy value is every value which is not falsy (null,false,0,"",undefined,NaN
)
Since "HelloWorld"
is indeed truthy
The expression ("HelloWorld" && "GoodbyeWorld")
evaluates to "GoodbyeWorld"
and you're effectively comparing
item.hello !== "GoodbyeWorld"
which can be reduced to "HelloWorld" !== "GoodbyWorld"
Hence, is true
However, if you're on an ES5 compatible environment you could use Array.prototype.indexOf
to simplify it.
!~["HelloWorld","GoodbyWorld"].indexOf(item.hello) //false
the above returns true if item.hello
is not contained in the array
No, you can't optimise the expression that way. What you are doing is elliminating one of the strings, so that you are only doing one of the comparisons.
The && operator uses short circuit evaluation, which means that if the first operand is truthy, it will just return the second operand.
So, what your code is doing is to compare the hello property value to the second one of the strings, which explains the results that you get.
item.hello !== "HelloWorld" && item.hello !== "GoodbyeWorld"
is the proper way to test whether item.hello
is distinct from "HelloWorld"
and "GoodbyeWorld"
.
An expression A && B
in JavaScript yields a result which is either A
or B
and it's that result, that is compared to your item.hello
.