Searching for elegant if [duplicate] - javascript

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.

Related

Why won't my JavaScript account system code work or run? [duplicate]

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.

if/else statement with prompt and || [duplicate]

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)) {
...
}

Properties and subproperties undefined check [duplicate]

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 : '';
}

How to check if a variable equals one of two values if a clean manner in JS [duplicate]

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
}

Is there a way to make this shorter with an Or operator? [duplicate]

This question already has answers here:
Check variable equality against a list of values
(16 answers)
Closed 3 years ago.
I would like to do this shorter?
function getRedditImg (img) {
if (img === 'default') {
return 'https://i.imgur.com/pMkc6Lo.png'
} else if (img === 'self') {
return 'https://i.imgur.com/pMkc6Lo.png'
}
return img
}
I tried doing this:
post.thumbnail === ( 'default' || 'self') ? 'https://i.imgur.com/pMkc6Lo.png' : post.thumbnail
But, it short circuits of default its true...
Any ideas? Thanks.
Do it witch the switch case syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

Categories