Karl Entwistle
Karl Entwistle

Reputation: 941

Why does `(var ||= true) = false` throw a syntax error?

I don't get why

(var ||= []) << 1

works as expected but

(var ||= true) = false

doesn't.

Could anyone explain why it doesnt work and what is going on here?

Upvotes: 2

Views: 215

Answers (2)

Julio Santos
Julio Santos

Reputation: 3895

a ||= b behaves like a || a = b.

An assignment returns the assigned value, i.e., var = true returns true.

var ||= true will evaluate to the assignment var = true, because var is undefined at that point. If var is defined and its value is true, it will return the value of var, that is true; if it's false, it will return the value of true, which is true.

var ||= [] returns [], and your first expression evaluated to [] << 1, which is legal.

However, your second expression evaluates to true = false, which throws a compile error.

tl;dr

(var ||= []) << 1(var = []) << 1[] << 1

(var ||= true) = false(var = true) = falsetrue = false

Upvotes: 12

Sony Santos
Sony Santos

Reputation: 5545

In the first case you have an object, and you uses its << method.

In the second case you have an assignment, where the right expression must be assigned to a variable on the left, not to an object or expression.

Upvotes: 3

Related Questions