undefined - Javascript - typeof in a ternary - Stack Overflow

I am trying type check for undefined in the first part of a ternaryreturn typeof this.scores != 'u

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742361545a4429491.html

相关推荐

  • undefined - Javascript - typeof in a ternary - Stack Overflow

    I am trying type check for undefined in the first part of a ternaryreturn typeof this.scores != 'u

    2小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信