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

Javascript if short notation - Stack Overflow

programmeradmin3浏览0评论

I was surfing on the web in search of a shorthand Javascript notation for an if-statement. ONLY the if, not the else. My question: does it exist? eg:

(i === 0) ? onlyMyTrueValue;

The only snippet I seem to find is this one:

(i === 0) ? myTrueValue : myFalseValue;

I was surfing on the web in search of a shorthand Javascript notation for an if-statement. ONLY the if, not the else. My question: does it exist? eg:

(i === 0) ? onlyMyTrueValue;

The only snippet I seem to find is this one:

(i === 0) ? myTrueValue : myFalseValue;
Share Improve this question edited Sep 4, 2014 at 15:17 Pablo Matias Gomez 6,8137 gold badges40 silver badges74 bronze badges asked May 20, 2013 at 16:13 user2381011user2381011 3516 silver badges21 bronze badges 2
  • 3 Google short-circuit evaluation. – Rob W Commented May 20, 2013 at 16:14
  • 2 The shorthand way to write an if statement is if(i===0)somevar=someval; but you should let a JS minifier handle that. – zzzzBov Commented May 20, 2013 at 16:15
Add a comment  | 

2 Answers 2

Reset to default 14

You can do:

(i === 0) && onlyMyTrueValue;

The right hand side of the above statement will execute only if the left hand side passes.

You could do (i === 0) && onlyMyTrueValue;, but you shouldn't, for readability sake.

Compare your original:

(i === 0) ? onlyMyTrueValue;

And plain old if:

if (i === 0) onlyMyTrueValue;

That's only one more character, and an identical number of characters to the && method. Go with the readable choice.

发布评论

评论列表(0)

  1. 暂无评论