最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

undefined - Javascript - typeof in a ternary - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Aug 23, 2018 at 18:56 LeBlaireauLeBlaireau 17.5k34 gold badges115 silver badges197 bronze badges 1
  • where is the : part? – Arup Rakshit Commented Aug 23, 2018 at 18:57
Add a ment  | 

3 Answers 3

Reset to default 5

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.

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();

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 plete your ternary expression.

发布评论

评论列表(0)

  1. 暂无评论