Skip to content
Advertisement

How do I eliminate all these if-else

I have written this code to filter a “books” array, depending on the author or genre have been given as a parameter:-

JavaScript

I believe there must be some way to write this more “professionally” without using all these if-else. So if anyone knows a better way, I’ll appreciate it.

[Edited] Thanks to all, I decided to go with ghostkraviz solution, code looks like this now:

JavaScript

Advertisement

Answer

since String.prototype.includes actually checks if a string maybe found within another string (the parameter) MDN String.prototype.includes. that means, for undefined args you could default it to empty string. Empty strings will return true if checked with .includes from any string.

you only check for 2 args which are the author & genre. here’s the example:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement