Shorthand for multiple OR expressions in if statement

Is there a shortcut for the following -

if(tld == "com" || tld == "net" || tld == "co" || tld == "org" || tld == "info" || tld == "biz") { //do something; } 
+7
source share
3 answers

you can use an array

 if(["","com","net","co","org","info","biz"].indexOf(tld) > -1) { // do something } 

or if you use jquery:

 $.inArray(tld, ["com","net","co","org","info","biz"]) 

REF - Operation Performance OR (||) vs inArray ()

+18
source

Use regex:

 if ( /^(com|net|co|org|info|biz)$/i.test(tld) ) { // do something } 
+12
source

Have you considered using the switch statement? something like that:

 switch(tld) { case 'com': case 'net': case 'co': ... ... // do something for all of them break; default: // if you want you can have default process here break; } 
0
source

Source: https://habr.com/ru/post/918596/


All Articles