Reputation: 21764
The following test generates an error if the response does not have a msgs[0]
property.
if response.msgs[0] === "published" { ... }
The error is:
Uncaught TypeError: Cannot read property '0' of undefined
How can I rewrite the test to generate an error? If there is no msgs[0]
property, I want the test to evaluate to false
.
Upvotes: 0
Views: 55
Reputation: 4229
Test if response.msgs
is defined first:
if response.msgs && response.msgs[0] === "published" { ... }
Upvotes: 3
Reputation: 943556
response does not have a msgs[0] property
This is incorrect. It throws an error because it doesn't have a msgs
property, not because there is no 0
property on it.
You need to test if msgs
exists before testing what 0
is.
if (response.msgs && response.msgs[0] === "published") { ... }
Upvotes: 7