Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: surprising order of operations

Tags:

javascript

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

like image 339
mkoryak Avatar asked Dec 08 '22 23:12

mkoryak


2 Answers

Your code is equivalent to

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

That's why. :)

like image 68
freakish Avatar answered Jan 03 '23 06:01

freakish


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.

like image 21
Guffa Avatar answered Jan 03 '23 04:01

Guffa