Javascript and / or Assignment Operators

I was looking at some compiled coffee code script, and I noticed something like the following, which in my opinion was really strange:

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

after doing this, the current has a value of 8. Judging by the fact that || the boolean operator works, I would expect it to evaluate the left side first. Having received "undefined" on the left side, it moves to the right, where it assigns this._head to 8. Then it returns true, but is this part not so important? I don’t see how it can return and affect the β€œcurrent” variable? Any help would be appreciated, thanks!

+4
source share
3 answers

Operator || returns a value, not true . Maybe it helps to say that

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

can also be written as

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

or

 current = this._head; if(!current) current = this._head = x; 
+1
source
  • Operator || returns the left side if it is "true", otherwise - on the right side - regardless of its likelihood. It does not pass the expression to the boolean true / false!
    • undefined || (this._head = x) undefined || (this._head = x) returns the right side
  • The assignment operator also returns a value!
    • this._head = x returns 8 in the above example
  • The first assignment operator assigns the value 8 to the current variable
+1
source

You can use expresion

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

Source: https://habr.com/ru/post/1399732/


All Articles