Using &&'s short-circuiting as an if statement?

非 Y 不嫁゛ 提交于 2019-11-26 17:44:22
deceze

Yes, your two examples are equivalent. It works like this in pretty much all languages, but it's become rather idiomatic in Javascript. Personally I think it's good in some situations but can be abused in others. It's definitely shorter though, which can be important to minimize Javascript load times.

Also see Can somebody explain how John Resig's pretty.js JavaScript works?

It's standard, but neither JSLint nor JSHint like it:

Expected an assignment or function call and instead saw an expression.

You must be careful because this short-circuiting can be bypassed if there is an || in the conditional:

false && true || true
> true

To avoid this, be sure to group the conditionals:

false && (true || true)
> false

Yes, it's equivalent to an if as you wrote. It's certainly not an uncommon practice. Whether it's accepted depends on who is (or isn't) doing the accepting...

Yes, you understand it (in that context); yes, it is standard practice in JavaScript.

By default, it will trigger a jshint warning:

[jshint] Expected an assignment or function call and instead saw an expression. (W030) [W030]

However personally, I prefer the short-circuit version, it looks more declarative and has "less control logic", might be a misconception though.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!