user1283776
user1283776

Reputation: 21764

Test a property only if it exists?

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

Answers (2)

Jieter
Jieter

Reputation: 4229

Test if response.msgs is defined first:

if response.msgs && response.msgs[0] === "published" { ... }

Upvotes: 3

Quentin
Quentin

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

Related Questions