Search code examples
javascriptlogical-operatorsshort-circuiting

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?


Solution

  • item.error || item.available is truthy.

    You need parentheses:

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