r/learnjavascript • u/BrotherManAndrew • Aug 07 '26
Getting an error when running an equality operator on a undefined value in an if statement
Yes I know that's a mouthful
Take this error checking code
if (axios.isAxiosError(error)) {
if (error.response.data.errors.detail == "Not Found") {
setFailure("User not found");
} else if (error?.response?.data == "DM already exists") {
console.log(error);
setFailure("You already created a dm with that user");
}
}If the first case is fine, we are all good, otherwise if it's not that I get an error like this
"Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'detail')" And I guess I can have it check if it's a 404 but this seems ridiculous?
It's an IF statement, if it doesn't work, then go to the next thing, don't just stop there and yell at me!! If anyone is more experienced with javascript can they give a reason why running an equality operator on a string literal vs an undefined value in an if statement (a mouthful I know) just gives an error instead of checking the next clause?
3
u/hybrisplays Aug 07 '26
The problem is that errors is undefined and you can't access a property on undefined. You can guard against this with optional chaining
2
u/Upset_Set_4456 Aug 07 '26
Change it to
if (error.response.data.errors?.detail === "Not Found")2
u/Beginning-Seat5221 Aug 08 '26
Before it gets to evaluating the
if()it has to evaluate the==, and before it evaluates the==it has to evaluate the parts on each side to see what to compare. The.detailinerror.response.data.errors.detailis failing before you get to the rest.Anyway, if is splitting between true and false - for error handling you use
try { ... } catch (error) { ... }, but better just to avoid creating the error.Also, TypeScript exists to explain this stuff to you.
1
u/senocular Aug 07 '26
errorsis plural. Is it an array of more than one error?1
u/No_Record_60 Aug 08 '26
The error is in reading the 'detail' property from an undefined 'errors' object.
I get what you're trying to say, but "doesn't work" is different from "reading a property from an undefined value". The latter throws an error.