Reputation: 435
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
Reputation: 272026
||
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 sidethis._head = x
returns 8 in the above examplecurrent
Upvotes: 1
Reputation: 2471
You can use expresion
var current=this._head ? this._head : (this._head = x);
Upvotes: 0
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