frc
frc

Reputation: 588

js strange return statement

I am doing an angular tutorial, but regardless, I do not understand the following return statement:

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

I tried rewriting it like so but it does not work:

if (selectedCategory == null) {
                return selectedCategory;
            } else {
                return product.category;
            }

How could the one liner code be rewritten so as to be more easily understood?

Upvotes: 0

Views: 43

Answers (2)

Bergi
Bergi

Reputation: 664297

How could the one liner code be rewritten so as to be more easily understood?

By putting some parenthesis around the returned expression:

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

It simply returns a boolean value. This should not be split up, using an if-statement makes it harder to read in fact. If at all, you could introduce some extra variables to give descriptive names to the single values:

// some guesses about their meaning
var noSelection   = selectedCategory == null;
var alreadyActive = product.category == selectedCategory;
var nothingTodo   = noSelection || alreadyActive;
return nothingTodo;

Upvotes: 0

epascarello
epascarello

Reputation: 207501

Yours returns null, theirs returns true. Yours would need to be

if (selectedCategory == null) {
    return true;
} else {
    return product.category == selectedCategory;
}

Upvotes: 2

Related Questions