Is there any difference between (cond && value || de

Is there any difference between (cond && value || default_value) and (cond ? value : default_value) in JavaScript?

本文关键字:amp de value cond any there difference between Is      更新时间:2023-09-26

这两个表达式似乎生成了相同的结果。它们之间有什么区别吗?

如果您的cond条件是truthy,但value不是,则第一个表达式将转到default_value,而第二个表达式将在cond为truthy后立即给出value,而不管实际的value是什么。

示例:

var cond = true,
    value = false,
    default_value = "whatever";
cond && value || default_value; // gives "whatever"
cond ? value : default_value; // gives `false`
value = "truthy";
cond && value || default_value; // gives "truthy"
cond ? value : default_value; // gives "truthy"
value = null; // or `undefined`, or "" (empty string), or any falsy value.
cond && value || default_value; // gives "whatever"
cond ? value : default_value; // gives `null` (or `undefined`, or "")
// or whatever is in `value`

现场演示:http://jsfiddle.net/artxvLab/