xcode xcode - 1 year ago 83
AngularJS Question

Short-hand boolean logic in JavaScript

I'm beginner on JavaScript and AngularJS. So I encounter following code from Adam Freeman books

var selectedCategory = null;
$scope.categoryFilterFn = function(product) {
return selectedCategory == null ||
product.category === selectedCategory;

I get confused by the
statement above, can you guys re-write the code above with clear code (no shorthand).


Answer Source

This is a short-hand form of returning a boolean value. Look closely:

 return selectedCategory == null || product.category === selectedCategory;

Here, return statement has two expressions:

  1. selectedCategory == null
  2. product.category === selectedCategory

When the method returns, it will evaluate these two expressions separately. Consider yout selectedCategory is null, and the product.category is equal to selectedCategory then the statement is

return true || true;

which will eventually simplifies to

return true; // (true || true) = true

Likewise, you can think of this expressions return value by substituting values and evaluate them separately.

Longer version for this is:

if (selectedCategory == null || product.category == selectedCategory) {
  return true;
} else {
  return false;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download