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'
will be "Thank You"
, and when that is evaluated as a boolean for the ?
operator, the result is true
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With