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

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

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

js 复制代码
const isFull = true; 
isFull && fixBug(); // 吃飽了 → 修Bug!

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

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

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

js 复制代码
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 : 请盖住右面联系哦

js 复制代码
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:短路求值

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

js 复制代码
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)

示例如下:

js 复制代码
// 女朋友问你前任照片在哪,只有真没存才安全
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 敏感→ 精准处理真空值

相关推荐
yuanyxh21 小时前
Mac 软件推荐
前端·javascript·程序员
万少21 小时前
AtomCode开发微信小程序《谁去呀》 全流程
前端·javascript·后端
某人辛木1 天前
Web自动化测试
前端·python·pycharm·pytest
Kagol1 天前
Superpowers GSD gstack AgentSkills深度测评
前端·人工智能
excel1 天前
JavaScript 字符串与模板字面量:从表象到本质理解
前端
京东云开发者1 天前
当AI成为导演-如何用AI创作动漫短剧
前端
李白的天不白1 天前
使用 SmartAdmin 进行前后端开发
java·前端
乘风gg1 天前
🤡PUA AI Coding 工具 的 10 条终极语录
前端·ai编程·claude
学Linux的语莫1 天前
Vue 3 入门教程
前端·javascript·vue.js
怕浪猫1 天前
第一章、Chrome DevTools Protocol (CDP) 详解
前端·javascript·chrome