DeepSeep 小课堂:&&、||、?? 的‘爱恨情仇’,看完直呼内行!

144 阅读2分钟

&&(逻辑与)—— "霸道总裁型"

场景:你的朋友求你帮忙修Bug,但你只有吃饱了才有力气

const isFull = true; 
isFull && fixBug(); // 吃飽了 → 修Bug!

isFull = false;
isFull && fixBug(); // 没吃饱 → 摆烂!

||(逻辑或)—— "备胎救场型"

场景:你约了朋友吃饭,但对方放鸽子,于是你找备胎

const date = null; // 朋友鸽了你
const backupFriend = '单身狗室友';

const dinnerPartner = date || backupFriend; 
console.log(dinnerPartner); // '单身狗室友'

||(逻辑或):左边的值为假(falsy),则返回右边的值;左边为真(truthy)返回左边的值。

falsy的值共6个

描述
false--
0数字零
""空字符串
null--
undefined--
NaN非数字

其他所有值都是真值(truthy)包括

描述
true--
非零数字如 1、-1
非空字符串--
对象如 "hello"
函数如 {}、[]

&& 与 ||的区别**

  • 逻辑与 && :左边为真值时返回右边。
  • 逻辑或 || :左边为假值时返回右边。

实战1 : 请盖住右面联系哦

console.log(0 || 1);                        // 1(左边为假值,返回右边)
console.log(0 && 1);                        // 0(左边为假值,返回左边)
console.log(1 || 2);                        // 1(左边为真值,返回左边)
console.log(1 && 2);                        // 2(左边为真值,返回右边)
console.log(0 && '你好');                   // 输出 0(左边为假,直接返回左边)
console.log('A' && null);                   // 输出 null(左边为真,返回右边)

实战2:短路求值

左边为真值,右边的表达式不会被执行。

function foo() {
  console.log("foo 被调用了");
  return true;
}

function bar() {
  console.log("bar 被调用了");
  return false;
}

console.log(foo() || bar());


// 输出:
// foo 被调用了
// true
// bar 不会被调用,因为 foo() 返回 true

??(空值合并)—— "精准识别型"

口诀:“除了真空,其他免谈”(只认 null/undefined)

示例如下:

// 女朋友问你前任照片在哪,只有真没存才安全
const exPhoto = undefined; 
const safeAnswer = '心里只有你!';

const result = exPhoto ?? safeAnswer; 
console.log(result); // '心里只有你!' ✅

// 对比 || 的翻车现场
const exPhoto = 0; // 前任照片数量是0张
console.log(exPhoto || safeAnswer); // '心里只有你!' 😱(明明删光了!)
console.log(exPhoto ?? safeAnswer); // 0 ✅(诚实但安全)

总结记忆法

&&:像 “安检门”,前面的人(左边)过了,才允许后面(右边)通过→ 条件成立 && 执行操作

||:像 “备胎列表”,第一个可用的直接上位→ 优先值 || 默认值

??:像 “非空检测仪”,只对 null/undefined 敏感→ 精准处理真空值