相信写前端开发的朋友对下面这种报错应该很熟悉:
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:变量被声明了,但还没赋值。
console.log(name); // undefined
null:程序员主动赋值为空,表示我明确知道这里没有值。
let user = null; // 表示“用户不存在”
判断方法
以下介绍了比较常用的几种判断方案。
方法一:显式比较(最保险)
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 ?? '匿名用户';
优势:只对 null 和 undefined 生效,不会误判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引擎优化得很好,但了解原理还是有帮助的:
== null 和显式比较性能相当
typeof 检查稍慢,但能安全检测未声明变量
可选链操作符在现代浏览器中性能优秀

没有绝对最好的方法,只有最适合当前场景的选择。根据你的具体需求和团队规范来决策吧!
参考文章:原文链接
该文章在 2026/1/9 14:39:18 编辑过