Day #5 Pro Tip #Javascript
Simplify if condition — Use indexOf
Published in
1 min readApr 5, 2018
Do you have one variable to be checked against multiple values ?
For e.g. Jack will be happy when he will get to eat Mango, Apple, Grapes or Guava
Trivial code is :
if(fruit === ‘Apple’ || fruit === ‘Mango’ || fruit === ‘Grapes’ || fruit === ‘Guava’) {
// Jack will be happy
}
But Jack is not happy with this code
Smart code is :
if([‘Apple’, ‘Mango’, ‘Grapes’, ‘Guava’].indexOf(fruit) > -1) {
// Jack will be happy
}
Read more about Array.prototype.indexOf
Thanks for reading
Stay tuned for more updates !!!