Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript how to use the and/or operator with parenthesis

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?

JSFiddle example

like image 746
Justus Romijn Avatar asked Dec 29 '25 07:12

Justus Romijn


2 Answers

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

like image 192
Matthew Mcveigh Avatar answered Dec 30 '25 23:12

Matthew Mcveigh


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

like image 45
Moritz Roessler Avatar answered Dec 31 '25 00:12

Moritz Roessler