xcode - 4 months ago 32

AngularJS Question

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

`return`

Thanks.

Answer

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:

`selectedCategory == null`

`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;
}
```