Javascript: amazing order of operations

I recently wrote code that didn't work as I would expect it to be:

message = 'Thank You'; type = 'success'; message = message || type == 'success' ? 'Success' : 'Error'; 

It seemed to me that at the end of this message was set to "Success" .

I would think that since the true value of the message is true , the right side of or will not be evaluated.

The brackets around the right side of the OR solved this, but I still don't understand why the right side was rated at all

+4
source share
2 answers

Your code is equivalent

 message = ( message || type == 'success' ) ? 'Success' : 'Error'; 

That's why.:)

+11
source

The message value does not end as "success" , but "success" .

The operator ? has a lower priority than the || , so the code evaluates to:

 message = (message || type == 'success') ? 'Success' : 'Error'; 

Result message || type == 'success' message || type == 'success' will be "Thank You" , and if it is evaluated as logical for the statement ? , the result will be true .

+3
source

All Articles