LeBlaireau
LeBlaireau

Reputation: 17467

Javascript - typeof in a ternary

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

Answers (3)

Willem van der Veen
Willem van der Veen

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

Alexander O'Mara
Alexander O'Mara

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

Nina Scholz
Nina Scholz

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

Related Questions