mmmmm
mmmmm

Reputation: 605

Not expected behavior while setting a string with short-circuit evaluation in Javascript

I want to use this short-circuit evaluation to report a nice status of multiple items in an one liner. But the result is not as expected as shown below:

var items = [{
    "id": 1,
    "available": true
}, {
    "id": 2,
    "available": false
}, {
    "id": 3,
    "error": "Server not found for that TLD"
}];

items.forEach(function(item) {
	console.log(item.id, item.error || item.available ? "Available" : "Not available");
});

This produced the following log:

1 "Available"
2 "Not available"
3 "Available"

At 3 I expected it to show the error because item.error is a string and should evaluate to `true, why does it skip it to item.available?

Upvotes: 1

Views: 69

Answers (2)

Matt Dyer
Matt Dyer

Reputation: 126

As @SLaks said parentheses will fix the problem. The order of operations is different than you expected. The || is evaluated before the ternary operator.

You can see the order here. Logical OR is just above the conditional operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

Upvotes: 1

SLaks
SLaks

Reputation: 887547

item.error || item.available is truthy.

You need parentheses:

item.error || (item.available ? "Available" : "Not available")

Upvotes: 2

Related Questions