4

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!

1
  • OH! I just realized I was getting hungup on operator precedence. The || operator happens before any value has been assigned to current. I was essentially imagining current = this._head having parentheses around it. thanks everyone! Commented Mar 5, 2012 at 11:44

3 Answers 3

1

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;
Sign up to request clarification or add additional context in comments.

Comments

1
  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

Comments

0

You can use expresion

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.