I recently wrote code that didnt work as i would expect, it was:
message = 'Thank You';
type = 'success';
message = message || type == 'success' ? 'Success' : 'Error';
It was news to me that at the end of that message
was set to 'Success' .
I would think that since the truthy value of message is true
, the right side of the or
would not evaluate.
Parenthesis around the right side of the OR solved this, but i still dont understand why the right side was evaluated at all
Your code is equivalent to
message = ( message || type == 'success' ) ? 'Success' : 'Error';
That's why. :)
The value of message
doesn't end up as "success"
but "Success"
.
The ?
operator has lower precedence than the ||
operator, so the code is evaluated as:
message = (message || type == 'success') ? 'Success' : 'Error';
The result of message || type == 'success'
message || type == 'success'
will be "Thank You"
, and when that is evaluated as a boolean for the ?
operator, the result is true
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.