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:
Why doesn't equality check work with arrays [duplicate]
(6 answers)
Closed 6 months ago.
const obj ={Rating:7.5 , Actor:[], Age:undefined}
want to remove Actor:[]
function clean(obj) {
for (var propName in obj) {
if (obj[propName] === undefined || obj[propName] == [] ) {
delete obj[propName];
}
}
return obj
}
this function is only removing undefined values
Two different javascript objects cannot be equal
to each other.
Below is a demo of that:
console.log([] === [])
console.log([] == [])
In your specific case you will have to check two things:
The value is an array.
The array is actually empty.
If both are true, then your expression should evaluate to true.
let arr = [];
let arr2 = [1];
if(Array.isArray(arr) && arr.length === 0){
console.log('isempty');
}
if(Array.isArray(arr2) && arr2.length === 0){
console.log('isempty');
}
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:
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:
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:
Shorthand for multiple OR expressions in if statement
(4 answers)
checking a variable value using an OR operator
(3 answers)
Closed 9 years ago.
i have this if statement and i wanna know if exist a better way to write it
if(i == "502" || i == "562" || i == "584" || i == "482" || i == "392"){
//Some Stuff here
}
That works fine. You can also use Array.indexOf
if(['502', '562', '584', '482', '392'].indexOf(i) !== -1)
{
/*Do Stuff*/
}
However, you should be careful with Array.indexOf because it is not supported by versions of Internet Explorer before IE9 :(. That is why $.inArray is often suggested over Array.indexOf.
Use $.inArray() method by jQuery:
var a = ['502', '562', '584', '482', '392'];
var i = '482';
if ($.inArray(i, a) > -1) {
alert(i);
}
References:
jQuery.inArray() - jQuery API Documentation
switch(i)
{
case 502:
case 562:
case 584:
case 482:
case 392: //do stuff
break;
}
While the other answers are very useful, they don't do exactly the same as your code. If you compare a string with only digits will compare equal (using ==) to a number it represents (and possibly other objects that have a toString() equal to that). But the same isn't true with indexOf, $.inArray or switch:
var i = 502;
i == "502"' // True
["502"].indexOf(i) // False
An exact equivalent of your code would be:
var VALUES = ['502', '562', '584', '482', '392'];
if(VALUES.some(function(e) { return e == i; }) {
// do something
}
Object lookups are pretty much as fast as variable lookups.
if ({
"502": 1,
"562": 1,
"584": 1,
"482": 1, // if you're concerned about conflict with `Object.prototype`
"392": 1 // then consider using `{...}[i] === 1` or
}[i]) { // `{...}.hasOwnProperty(i)`
// code if found
}
Be aware that this method won't let you make the distinction between i === 502 and i === '502' as all keys in Objects are Strings.