普通视图

发现新文章,点击刷新页面。
昨天 — 2026年1月8日首页

JavaScript 中如何正确判断 null 和 undefined?

2026年1月8日 11:34

相信写前端开发的朋友对下面这种报错应该很熟悉:

Cannot read properties of undefined

有一次我加班处理问题,也是因为这一个bug。

后来才发现,原来是一个接口返回的数据里,某个字段有时候是null导致的,而我没有做判断就直接使用了。

一、为什么需要判断空值?

举例如下:

// 场景1:用户没填姓名
const userName = undefined;
console.log(userName.length); // 报错!Cannot read properties of undefined

// 场景2:接口返回空数据
const apiResponse = null;
console.log(apiResponse.data); // 报错!Cannot read properties of null

所以,空值判断是保证代码健壮性的重要环节。


二、先搞懂:null 和 undefined 有啥区别?

虽然它们都表示空,但含义不同:

undefined:变量被声明了,但还没赋值。

let name;
console.log(name); // undefined

null:程序员主动赋值为空,表示我明确知道这里没有值。

let user = null; // 表示“用户不存在”

所以,当我们说判断变量是否为空,通常是指:它是不是 nullundefined


判断方法

以下介绍了比较常用的几种判断方案。

方法一:显式比较(最保险)

if (variable === null || variable === undefined) {
  console.log('变量为空');
}

适用场景

  • 需要明确区分null和undefined时
  • 团队代码规范要求严格相等判断
  • 对代码可读性要求高的项目

案例

function getUserProfile(user) {
  if (user === null || user === undefined) {
    return '用户不存在';
  }
  return `欢迎,${user.name}`;
}

方法二:非严格相等(最常用)

if (variable == null) {
  console.log('变量为空');
}

这里有个重要知识点== null 实际上等价于 === null || === undefined,这是JavaScript的语言特性。

为什么推荐这个写法?

  • 代码简洁,少写很多字符
  • 性能优秀,现代JS引擎都做了优化
  • 意图明确,专业开发者一看就懂

方法三:逻辑非操作符

if (!variable) {
  console.log('变量为falsy值');
}

注意! 这个方法容易造成其它的误伤:

// 这些值都会被判断为"空"
!false      // true
!0         // true  
!""        // true
!NaN       // true

// 实际开发中的坑
const count = 0;
if (!count) {
  console.log('计数为0'); // 这里会执行,但可能不是我们想要的
}

方法四:typeof 关键字(安全的写法)

if (typeof variable === 'undefined' || variable === null) {
  console.log('变量是空的!');
}

安全在哪?

// 如果变量根本没声明,前两种方法会报错
if (notDeclaredVariable == null) { // 报错!ReferenceError
}

if (typeof notDeclaredVariable === 'undefined') { // 正常运行!
  console.log('变量未定义');
}

这种写法主要用于检查一个变量是否被声明过,但对于普通函数参数或已声明变量,没必要这么复杂。

适用于不确定变量是否声明的场景。


方法五:空值合并操作符(现代写法)

这是ES2020的新特性,用起来特别顺手:

// 传统写法
const name = username ? username : '匿名用户';

// 现代写法
const name = username ?? '匿名用户';

优势:只对 nullundefined 生效,不会误判0、false等其他值。


方法六:可选链操作符(对象属性专用)

处理嵌套对象时,这个功能简直是救命稻草:

// 以前的痛苦写法
const street = user && user.address && user.address.street;

// 现在的优雅写法
const street = user?.address?.street;

结合空值合并,写法更加安全:

const street = user?.address?.street ?? '地址未知';

实际开发中的建议

场景1:简单的空值检查

// 推荐
if (value == null) {
  // 处理空值
}

// 或者
const safeValue = value ?? defaultValue;

场景2:需要区分null和undefined

if (value === null) {
  console.log('明确设置为空');
}

if (value === undefined) {
  console.log('未定义');
}

场景3:处理对象属性

// 安全访问深层属性
const phone = order?.customer?.contact?.phone ?? '未填写';

场景4:函数参数默认值

function createUser(name, age = 18) {
  // age参数只在undefined时使用默认值
  return { name, age };
}

总结

虽然现代JavaScript引擎优化得很好,但了解原理还是有帮助的:

  1. == null 和显式比较性能相当
  2. typeof 检查稍慢,但能安全检测未声明变量
  3. 可选链操作符在现代浏览器中性能优秀
场景 推荐写法 原因
一般空值检查 value == null 简洁高效
需要明确意图 value === null value === undefined` 可读性强
设置默认值 value ?? defaultValue 安全准确
对象属性访问 obj?.prop 避免报错
函数参数 参数默认值 语言特性

没有绝对最好的方法,只有最适合当前场景的选择。根据你的具体需求和团队规范来决策吧!

本文首发于公众号:程序员大华,专注分享前后端开发的实战笔记。关注我,少走弯路,一起进步!

📌往期精彩

16 个前端冷知识:用一次就忘不掉的那种

我也是写了很久 TypeScript,才意识到这些写法不对

ThreadLocal 在实际项目中的 6 大用法,原来可以这么简单

重构了20个SpringBoot项目后,总结出这套稳定高效的架构设计

❌
❌