Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 459
LeBlaireau Avatar asked Nov 17 '25 18:11

LeBlaireau


2 Answers

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.

like image 119
Alexander O'Mara Avatar answered Nov 19 '25 09:11

Alexander O'Mara


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();
like image 24
Nina Scholz Avatar answered Nov 19 '25 08:11

Nina Scholz