??
空值合并运算符,a??b 的返回结果是,如果a被定义了,那就返回a,如果a没有被定义,那么就返回b。返回第一个不是null/undefined的参数
let user; alert(user??"Anonymous")//返回Anonymous
let user = "John"; alert(user ?? "Anonymous"); //返回John
let firstName = null; let lastName = null; let nickName = "Supercoder"; // shows the first defined value: alert(firstName ?? lastName ?? nickName ?? "Anonymous");//返回Supercoder
与||的区别
let height = 0; alert(height || 100); // 100 alert(height ?? 100); // 0
??的话因为height已经被初始化就返回0,||的话0也是一个假值,所以返回100