This question already has answers here:
Check variable equality against a list of values
(16 answers)
Closed 2 years ago.
I have a condition:
if (item == 'a' || item == 'b' || item == 'c' || item == 'd' || item == 'e') {
// statements
}
How can I reduce the branching? Is there any other way to write this in JavaScript.
You can also use the newer Array.includes
if (['a','b','c','d','e'].includes(item)) {
...
}
Another option (for the very specific case you posted) would be to compare unicode point values using </>
if (item >= 'a' && item <= 'e') {
...
}
Use Array#indexOf method with an array.
if(['a','b','c','d','e'].indexOf(item) > -1){
//.........statements......
}
You can use an array as shown below.
var arr = ['a','b','c','d','e'];
if(arr.indexOf(item) > -1)
{
//statements
}
This would work nicely:
if('abcde'.indexOf(item) > -1) {
...
}
You could also use the newer String.prototype.includes(), supported in ES6.
if('abcde'.includes(item)) {
...
}
Related
This question already has answers here:
Check variable equality against a list of values
(16 answers)
Concise way to compare against multiple values [duplicate]
(8 answers)
Closed 7 years ago.
Whats the prettiest way to compare one value against multiples options?
I know there are loads of ways of doing this, but I'm looking for the neatest.
i ask because i'd hoped this was workable (it isn't, quite obviously when you look at it):
if (foobar == (foo||bar) ) {
//do something
}
Don't try to be too sneaky, especially when it needlessly affects performance.
If you really have a whole heap of comparisons to do, just format it nicely.
if (foobar === foo ||
foobar === bar ||
foobar === baz ||
foobar === pew) {
//do something
}
What i use to do, is put those multiple values in an array like
var options = [foo, bar];
and then, use indexOf()
if(options.indexOf(foobar) > -1){
//do something
}
for prettiness:
if([foo, bar].indexOf(foobar) +1){
//you can't get any more pretty than this :)
}
and for the older browsers:
( https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/IndexOf )
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
Since nobody has added the obvious solution yet which works fine for two comparisons, I'll offer it:
if (foobar === foo || foobar === bar) {
//do something
}
And, if you have lots of values (perhaps hundreds or thousands), then I'd suggest making a Set as this makes very clean and simple comparison code and it's fast at runtime:
// pre-construct the Set
var tSet = new Set(["foo", "bar", "test1", "test2", "test3", ...]);
// test the Set at runtime
if (tSet.has(foobar)) {
// do something
}
For pre-ES6, you can get a Set polyfill of which there are many. One is described in this other answer.
You can use a switch:
switch (foobar) {
case foo:
case bar:
// do something
}
Just for kicks, since this Q&A does seem to be about syntax microanalysis, a tiny tiny modification of André Alçada Padez's suggestion(s):
(and of course accounting for the pre-IE9 shim/shiv/polyfill he's included)
if (~[foo, bar].indexOf(foobar)) {
// pretty
}
Why not using indexOf from array like bellow?
if ([foo, bar].indexOf(foobar) !== -1) {
// do something
}
Just plain Javascript, no frameworks or libraries but it will not work on IE < 9.
(foobar == foo || foobar == bar) otherwise if you are comparing expressions based only on a single integer, enumerated value, or String object you can use switch. See The switch Statement. You can also use the method suggested by André Alçada Padez. Ultimately what you select will need to depend on the details of what you are doing.
I like the pretty form of testing indexOf with an array, but be aware, this doesn't work in all browsers (because Array.prototype.indexOf is not present in old IExplorers).
However, there is a similar way by using jQuery with the $.inArray() function :
if ($.inArray(field, ['value1', 'value2', 'value3']) > -1) {
alert('value ' + field + ' is into the list');
}
It could be better, so you should not test if indexOf exists.
Be careful with the comparison (don't use == true/false), because $.inArray returns the index of matching position where the value has been found, and if the index is 0, it would be false when it really exist into the array.
This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
Is there an easier way to determine if a variable is equal to a range of values, such as:
if x === 5 || 6
rather than something obtuse like:
if x === 5 || x === 6
?
You can stash your values inside an array and check whether the variable exists in the array by using [].indexOf:
if([5, 6].indexOf(x) > -1) {
// ...
}
If -1 is returned then the variable doesn't exist in the array.
Depends on what sort of test you're performing. If you've got static strings, this is very easy to check via regular expressions:
if (/^[56ab]$/.test(item)) {
//-or-
if (/^(foo|bar|baz|fizz|buzz)$/.test(item)) {
doStuff();
} else {
doOtherStuff();
}
If you've got a small set of values (string or number), you can use a switch:
switch (item) {
case 1:
case 2:
case 3:
doStuff();
break;
default:
doOtherStuff();
break;
}
If you've got a long list of values, you should probably use an array with ~arr.indexOf(item), or arr.contains(item):
vals = [1,3,18,3902,...];
if (~vals.indexOf(item)) {
doStuff();
} else {
doOtherStuff();
}
Unfortunately Array.prototype.indexOf isn't supported in some browsers. Fortunately a polyfill is available. If you're going through the trouble of polyfilling Array.prototype.indexOf, you might as well add Array.prototype.contains.
Depending on how you're associating data, you could store a dynamic list of strings within an object as a map to other relevant information:
var map = {
foo: bar,
fizz: buzz
}
if (item in map) {
//-or-
if (map.hasOwnProperty(item)) {
doStuff(map[item]);
} else {
doOtherStuff();
}
in will check the entire prototype chain while Object.prototype.hasOwnProperty will only check the object, so be aware that they are different.
It's perfectly fine. If you have a longer list of values, perhaps you can use the following instead:
if ([5,6,7,8].indexOf(x) > -1) {
}
Yes. You can use your own function. This example uses .some:
var foo = [ 5, 6 ].some(function(val) {
return val === x;
});
foo; // true
This is what I've decided to use:
Object.prototype.isin = function() {
for(var i = arguments.length; i--;) {
var a = arguments[i];
if(a.constructor === Array) {
for(var j = a.length; j--;)
if(a[j] == this) return true;
}
else if(a == this) return true;
}
return false;
}
You would use it like this:
var fav = 'pear',
fruit = ['apple', 'banana', 'orange', 'pear'],
plu = [4152, 4231, 3030, 4409];
if (fav.isin(fruit, plu, 'eggs', 'cheese')) {
//do something cool
}
The advantages are:
it works in IE < 9;
it reads naturally from left to right;
you can feed it arrays or separate values.
If you don't want to allow type coercion (indexOf does not), change the two == to ===. As it stands:
fav = "4231";
plu.indexOf(fav) //-1
fav.isin(plu) //true
no, there might be a few tricks that are case specific but in general i write code like this:
if (someVariable === 1 ||
someVariable === 2 ||
someVariable === 7 ||
someVariable === 12 ||
someVariable === 14 ||
someVariable === 19) {
doStuff();
moreStuff();
} else {
differentStuff();
}
The simple answer is no. You can use a switch statement, which is easier to read if you are comparing a lot of string values, but using it for two values wouldn't look any better.
[Edit] this seems to work, but as Dan pointed out, it is actually a false positive. Do not use this method. I leave it here for educational purposes.
Easiest way I know :
a = [1,2,3,4,5];
if(3 in a) alert("true"); // will alert true
Tested in Chrome console. Not sure if it works in other browsers.
This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 2 years ago.
I currently have this JavaScript function lying around within my code:
getCoverPhoto(item) {
if (item != undefined && item.gallery != undefined && item.gallery[0] != undefined)
return item.gallery[0].media;
return "";
}
How can I simplify the if condition above? And if it can't be simplified, can it be written in a better way?
For example with ternary operator:
getCoverPhoto(item) {
return item && item.gallery && item.gallery[0] ? item.gallery[0].media : '';
}
Read further in the documentation:
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as a shortcut for the if statement.
Or with ES6+:
const getCoverPhoto = item => item && item.gallery && item.gallery[0] ? item.gallery[0].media : '';
I hope that helps!
Here is a more simplified version of your code.
getCoverPhoto(item) {
if (item && item.gallery && item.gallery[0])
return item.gallery[0].media;
return "";
}
Use destructing to reduce the conditions. Below code should work for you.
getCoverPhoto(item) {
const { gallery = [] }= item; // this is destructing with default value assignment.
return item.gallery[0] ? item.gallery[0].media : '';
}
This question already has answers here:
Check variable equality against a list of values
(16 answers)
Closed 3 years ago.
To check if x variable is equal to 1 or 2, i would do normally something like:
if (x === 1 || x === 2){
// ....
}
but this can get in some cases very cumbersome.
Edit :I'm working right now on this and writing the fonction name every time i think can be done in a cleaner manner:
if (
this.getNotificationStatus() === 'denied' ||
this.getNotificationStatus() === 'blocked'
)
Is there any other lighter way to write this?
THANKS
You could do:
if ([1, 2].includes(x)) {
// ....
}
Or:
if ([1, 2].indexOf(x) > -1) {
// ....
}
Or:
switch (x) {
case 1:
case 2:
// ....
break;
default:
}
I don't think they're "lighter" than your solution though.
Try this:
if ([1, 2, 3].includes(x)) {
// your code here
}
This question already has answers here:
Reduce multiple ORs in IF statement in JavaScript
(8 answers)
Closed 5 years ago.
Is there more elegant way for this if?
if (err.code === 'CONFLICT-GROUP-GENERAL' ||
err.code === 'CONFLICT-USER-GENERAL' ||
err.code === 'CONFLICT-FORM-GENERAL' ||
err.code === 'CONFLICT-PROJECT-GENERAL' ||
err.code === 'CONFLICT-TEMPLATE-GENERAL') {}
I would be better off with an array with all the codes and use indexOf to check if it's greater than -1:
if (['CONFLICT-GROUP-GENERAL', 'CONFLICT-USER-GENERAL', 'CONFLICT-FORM-GENERAL', 'CONFLICT-PROJECT-GENERAL', 'CONFLICT-TEMPLATE-GENERAL'].indexOf(err.code) > -1) {
}
This trick seems to me more elegant (using an array and indexOf):
var conflicts = ['CONFLICT-GROUP-GENERAL',
'CONFLICT-USER-GENERAL',
'CONFLICT-FORM-GENERAL',
'CONFLICT-PROJECT-GENERAL',
'CONFLICT-TEMPLATE-GENERAL'];
if (conflicts.indexOf(err.code) !== -1) {
doSomething();
}
If you are using ES7 then you can use includes() instead of indexOf. This will be more "expressive":
var conflicts = ['CONFLICT-GROUP-GENERAL',
'CONFLICT-USER-GENERAL',
'CONFLICT-FORM-GENERAL',
'CONFLICT-PROJECT-GENERAL',
'CONFLICT-TEMPLATE-GENERAL'];
if (conflicts.inclues(err.code)) {
doSomething();
}
Note that includes() will not be suported by all browsers.
EDIT:
Another alternative: Using a switch. This way:
switch (err.code) {
case 'CONFLICT-GROUP-GENERAL',:
case 'CONFLICT-USER-GENERAL',:
case 'CONFLICT-FORM-GENERAL',:
case 'CONFLICT-PROJECT-GENERAL',:
case 'CONFLICT-TEMPLATE-GENERAL':
doSomething();
break;
}
The code above will execute the doSomething() function when err.code is equal to one of specified strings in each case.