JavaScript: Checking If A Given Value Is One Of Many

Suppose you have have a variable language and you want to decide which country it is generally spoken in. Traditional approach would be to use disjunction of multiple comparisons:

if (language === 'urdu' || language === 'punjabi' || language === 'pashto' || language === 'sindhi' || language === 'balochi') {
    console.log('This language is spoken in Pakistan.');
} else if (language === 'hindi' || language === 'gujrati' || language === 'bihari') {
    console.log('This language is spoken in India.');
} else {
    console.log('Could not identify region of this language.');
}

However a small trick can help us to do same task in much lesser characters:

if (['urdu', 'punjabi', 'pashto', 'sindhi', 'balochi'].indexOf(langauge) > -1) {
    console.log('This language is spoken in Pakistan.');
} else if (['hindi', 'gujrati', 'bihari'].indexOf(language) > -1) {
    console.log('This language is spoken in India.');
} else {
    console.log('Could not identify region of this language.');
}

Basically, in each condition, we create an array of all possible options, and check if current item is contained in the array. Please share your thoughts in comments.

Published by

Umar Ashfaq

Umar Ashfaq is a full-stack web developer. His core strength is building neat UIs with JavaScript on web but he also enjoys server side Java, NodeJS and Objective C. Follow him on twitter @umarashfaq87

Leave a Reply

Your email address will not be published. Required fields are marked *