NdaJunior
NdaJunior

Reputation: 374

Trying to return a default string if condition fails

Im building a soccer(football) scheduling app using react.js and one of the things I'm trying to do is iterate through an object which contains the teams that are playing.

I'd like to pull out various properties from this object and if any of these properties are missing, I return a string that says "Not Playing". This is what I have however, whenever a property doesnt exist, it throws an error rather than defaulting to "Not Playing":

{(this.state.contest.matches[this.state.player.team.name].home + " vs " +(this.state.contest.matches[this.state.player.team.name]).away) ||  ("Not Playing") }

Any idea how I can fix this?

Upvotes: 0

Views: 46

Answers (2)

Mahmoud
Mahmoud

Reputation: 81

if by missing you mean undefined you can use the following code:

(typeof this.state.contest.matches[this.state.player.team.name].away != "undefined")  ? this.state.contest.matches[this.state.player.team.name].away : "Not Playing";

Upvotes: 1

ashtrail
ashtrail

Reputation: 93

You shoud try something like

if (!property1 || !property2)
    return "default string";
else
    return property1 + "vs" + property2;

Upvotes: 0

Related Questions