The verbiage was a little awkward here but I know there's a smart way to go about this. I am requesting data from a JSON object. This JSON object will either have a "city", "town", or "locale". It will only ever have one. I have some verbose layered 'if undefined' checks that just stack on top of each other until I find the right one, but I imagine using operators there must be a better way. This code works, I just believe it can it should be done better. Here's an example:
var town = response.data["locale"];
if(town === undefined){
town = response.data["town"];
if(town === undefined){
town = response.data["city"];
if(town === undefined){
town = "N/A";
}
}
}
As you can see I just want to assign my variable to whichever one exists. I find this nested "if statement" mess a complete eyesore. Perhaps my problem can help people in the future write cleaner code. I'm not great with operators but this situation doesn't seem to call for use of any ternary operators.
You can use the or (||
) operator while defining a variable for example. It checks if the first one is undefined, and if it is, it will try to use the second one, etc.
In your case, you can just replace it to this line.
let town = response.data["locale"] || response.data["town"] || response.data["city"] || "N/A";