I downloaded a weather API to get the value of the current conditions, which all works well except for the alert "event" and "description".
If an "alert" exists I get the value, but when there is none, the result is "TypeError: Cannot read property '0' of undefined".
What I need is an IF statement that says "if undefined, "0" else get the value" for these two lines:
const alerts = resJSON["alerts"][0]["event"]
const alertDs = resJSON["alerts"][0]["description"]
You could use optional chaining
const resJSON = {alerts: [{notevent: "test", description: "my description"}]};
const alerts = resJSON?.alerts?.[0]?.event || "0";
const alertDs = resJSON?.alerts?.[0]?.description || "0";
console.log(alerts);
console.log(alertDs);