[Vuejs]-Javascript if statement inside return

2👍

You can do this, only apply the search if the property is truthy like this:

This is called

Short-circuit evaluation

 return (
      (game.venue && game.venue.toLowerCase().search(this.searchTerm.venue) >= 0) &&
      (game.date && game.date.search(this.searchTerm.date) >= 0) &&
      (game.price && game.price.search(this.searchTerm.price) >= 0)
    );

It works because in JavaScript, true && expression always evaluates to expression, and false && expression always evaluates to false.

Edit Using || to return true even if 1 search matches:

return (
          (game.venue && game.venue.toLowerCase().search(this.searchTerm.venue) >= 0) ||
          (game.date && game.date.search(this.searchTerm.date) >= 0) ||
          (game.price && game.price.search(this.searchTerm.price) >= 0)
        );

Edit 2 To filter only and all the values entered by the user and ignore the others:

return (
        (!game.venue || game.venue.toLowerCase().search(this.searchTerm.venue) >= 0) &&
        (!game.date || game.date.search(this.searchTerm.date) >= 0) &&
        (!game.price || game.price.toString().search(this.searchTerm.price) >= 0)
      );

Leave a comment