When checking a short list of variables for being within a set, what structure is most efficient.
if(checkString === 'string1'
|| checkString === 'someString2'
|| checkString === 'differentString3'
|| checkString === 'lol'
|| checkString === 'jsIsFun'
){doThing();}
For readability I would prefer one of the following:
if(['string1', 'string2','differentString3', 'lol', 'jsIsFun'].includes(checkString)){
doThing();
}
or:
switch (checkString) {
case 'string1':
case 'string2':
case 'differentString3':
case 'lol':
case 'jsIsFun':
doThing();
break;
}
For a touch of background, I am trying to tidy chains of if-else with a similar structure to the first example. The checkString
has a relatively even distribution of items it would expect to match in the set.
The structure of the data is not already in an array, so I am wondering if there is any meaningful memory cost to initializing an array for using ‘includes’.
Is one of the above methods the most efficient for vanilla JS, or is there a better way to check for string belonging to a state.