Nested ifs to test if one or both of two conditions is true
-
23-02-2021 - |
Question
I have an object, data
, that may or may not contain the members site_with_same_coords
and/or site_with_same_name
. I test for these and if one or both exist, I alerts to the user:
if (data.site_with_same_coords){
var SameCoordsExists = true;
same_coords_message = 'The site ';
same_coords_message += data.site_with_same_coords.name;
same_coords_message += 'already already exists in the location you have indicated';
}
if (data.site_with_same_name){
var SameNameExists = true;
same_name_message = 'The site ';
same_name_message += data.site_with_same_name.name;
same_name_message += 'already already exists in a differnt location from the one you have indicated';
}
if (SameCoordsExists && SameNameExists){
if(data.site_with_same_name.id != data.site_with_same_coords.id){
alert(same_coords_message + '\n' + same_name_message);
}else if (SameCoordsExists){
alert(same_coords_message);
}
}else if (SameNameExists){
alert(same_name_message);
}
}
Is there a better way of doing this?
Solution
Sure, you could put them in an array and join them:
var messages = [];
if(data.site_with_same_coords) {
messages.push('The site ' + data.site_with_same_coords.name + ' already exists in the location you have indicated');
}
if(data.site_with_same_name && !(data.site_with_same_coords && data.site_with_same_name.id === data.site_with_same_coords.id)) {
messages.push('The site ' + data.site_with_same_name.name + ' already exists in a different location from the one you have indicated');
}
alert(messages.join('\n'));
Also, wouldn't the user be a bit confused if they received the message:
The site some_site already exists in the location you have indicated
The site some_other_site already exists in a different location from the one you have indicated
? Just a thought.
OTHER TIPS
This skeleton:
if (A && B) {
if (C)
print(msgA);
print(msgB);
} else {
print(msgA);
}
can be rewritten like this:
var AB = A && B;
if ((AB && C) || !AB)
print(msgA);
if (AB)
print(msgB);
as you can see, msgA
and msgB
appear only once, so you can create the strings on the fly right where they're printed. Obviously, in your case, A
would be data.site_with_same_coords
, B
would be data.site_with_same_name
and C would be data.site_with_same_name.id != data.site_with_same_coords.id
.
It goes without saying that the rewritten version is much less readable.
update: if you really need to alert() then you'd do:
var AB = A && B;
if ((AB && C) || !AB)
msg += msgA;
if (AB)
msg += msgB;
if (msg)
alert(msg);