js逻辑运算符&&的短路操作,有哪些具体应用?

目前在别人代码里,只看过以下这种应用,还有更多的应用示例吗?MDN:&&操作符的短路操作

//执行回调(&&的短路操作可作为类型检查)
typeof callback === 'function' && callback();
阅读 5.2k
4 个回答
if(条件) {
    函数();
}
// 可以写成
条件 && 函数();
if(变量未定义) {
    变量 = 默认值;
}
// 可以写成
变量 = 变量 || 默认值;

check to avoid "property of undefined" ex:

if(req&&req.query&&req.query.id){
    // do something with req.query.id.
}


The example you given is also a check: it wants to make sure the callback is a function and then use it.

你要清楚短路是干嘛的
(1) && (1)

代码块1是true,就执行代码块2
推荐问题