RJK
RJK

Reputation: 242

JavaScript && Operator Without =

I came across this line:

while (char = word[i++]) {
  if (!current[char]) { break; }
  current = current[char];
  prefix += char;
  current.word && found.push(prefix); //??
}

What does the AND (current.word && found.push(prefix)) operator mean in this situation?

Is this the equivalent to both those expressions being true? I tried separating the expressions and set to true but I do not think that is the equivalent...

Upvotes: 0

Views: 47

Answers (1)

adeneo
adeneo

Reputation: 318202

&& checks if both expression on either side are truthy, i.e. that this AND this are both truthy.

The specs says

Logical AND (&&) expr1 && expr2
Returns expr1 if it can be converted to false; otherwise, returns expr2.
Thus, when used with Boolean values, && returns true if both operands can be converted to true; otherwise, returns false.

It always checks from left to right, starting with the left side expression

Knowing this, if the expression on the left side of && is falsy, there's no reason to check the right side, as the result will be falsy if the first expression is falsy.

In other words, if current.word is falsy, it ends there.
If current.word is truthy, it has to check the right side of && as well, and executes the found.push(prefix) to see if that expression is falsy or truthy.

More simply, it could be written

if ( current.word ) found.push(prefix);

but someone was being clever

Upvotes: 4

Related Questions