elju
elju

Reputation: 435

Javascript or and assignment operators

I was looking through some compiled coffee-script code, and I noticed something like the following, which I thought was really strange:

var current, x = 8;
current = this._head || (this._head = x);

after running this, current has a value of 8. Judging by the way that the || logical operator works, I would have expected it to evaluate the left side first. After getting an 'undefined' on the left hand side, it moves onto the right, where it assigns this._head to 8. Afterwards it returns a true, but this part isn't that important? I don't see how it could go back and affect the "current" variable? Any help would be appreciated, thanks!

Upvotes: 4

Views: 100

Answers (3)

Salman Arshad
Salman Arshad

Reputation: 272026

  1. The || operator returns the left hand side if it is "truthy", otherwise, the right hand side -- regardless of its truthiness. It does not cast the expression to the boolean true/false!
    • undefined || (this._head = x) returns the right hand side
  2. The assignment operator also returns a value!
    • this._head = x returns 8 in the above example
  3. The first assignment operator assigns the value 8 to the variable current

Upvotes: 1

Kunal Vashist
Kunal Vashist

Reputation: 2471

You can use expresion

var current=this._head ? this._head : (this._head = x);

Upvotes: 0

James M
James M

Reputation: 16718

The || operator returns the value, not true. Maybe it helps to say that

current = this._head || (this._head = x)

could also be written as

current = this._head ? this._head : (this._head = x);

or

current = this._head;

if(!current)
    current = this._head = x;

Upvotes: 1

Related Questions