Reputation: 17467
I am trying type check for undefined in the first part of a ternary
return typeof this.scores != 'undefined' ? this.scores.filter()
and
return (typeof this.scores != 'undefined') ? this.scores.filter()
Do I have to use a full if/else?
Upvotes: 2
Views: 3547
Reputation: 36620
Try thinking of the problem step wise in the following manner:
this.scores != 'undefined'
Is an expression which returns true if this.scores
is any other value than undefined
Let's say this.scores
is not undefined, now we are left with the following:
return true ? this.scores.filter()
This would not be valid JS because a ternary expression needs to have a true and false case separated with a colon. We can fix this in the following manner without an if else statement:
return true ? this.scores.filter() : null
Remember the ternary expression is (of course) an expression, which means that it returns a value. this value then in turn can be returned by the return
statement you already have in the beginning.
To conclude, no if else
statement is needed when you complete your ternary expression.
Upvotes: 0
Reputation: 60527
What you have will work if you finish the ternary expression:
return typeof this.scores != 'undefined' ? this.scores.filter() : null;
You can replace null
with whatever value you want to return instead.
Upvotes: 5
Reputation: 386620
You could return an undefined
or the value of the function call by using a logical AND &&
instead of a conditional (ternary) operator ?:
without an else part (which is not possible).
return this.scores && this.scores.filter();
Upvotes: 3