?. , ??, ??= usage and usage scenarios in JS

foreword

a439ddeb07771e91777a6bb2384aece2.jpegI believe that many front-end engineers have encountered this error, and it is inevitable that they will encounter it during the development process. Either it is caused by incomplete consideration, or it is caused by returning data or transmitting data in the background. Therefore, making non-empty judgments has become an indispensable thing. The following introduces some new es6 grammars for our development.

  1. optional chaining operator

    1.1 The optional chain operator allows you to check whether an intermediate property exists or is null/undefined when accessing object properties or calling functions. If the intermediate property does not exist or is empty, the expression will short-circuit and return undefined without raising an error.

    let obj = { 
       data: {
           third: 43
       }
    }
    console.log(obj?.data?.third) // 使用可选链式操作符后,只要前面有一个属性为空或者undefined,即返回undefined,不会引发错误
    
    在传统判断写法中,我们通常会这么做,需要手动检查某个属性,或者是具体业务中使用if判断某个属性是不是为 null 或 undefined
    obj && obj.data && obj.data.third

    1.2 Usage Scenarios

    调用可能为 null 或 undefined 属性的时候
    链式访问某个对象的属性的时候,不必在手动检查某个属性
  2. null coalescing operator

    2.1 Null value coalescing operator, that is, when the value of the variable is null and undefined, provide a default value for the variable, otherwise return the value of the variable itself

    'hello world' ?? 'hi' 
    // 'hello world' 
    '' ?? 'hi' 
    // '' 
    false ?? 'hi' 
    // false 
    null ?? 'hi' 
    // 'hi' 
    undefined ?? 'hi' 
    // 'hi'
    **在传统写法中,空字符串以及0,转布尔类型是false,会被默认为假,而在新的语法中,成功的兼容了此问题**

    2.2 Usage Scenarios

    提供默认值,而不使用 falsy 值(如空字符串、0 等)
    在处理可能为 null 或 undefined 的变量时,选择性地提供备用值
  3. null-coalescing assignment operator

    3.1 When ??= the value on the left is null or undefined, the value of the variable on the right will be assigned to the variable on the left, and all other values ​​will not be assigned

    let b = '你好'; 
    let a = 0;
    let c = null; 
    let d = '123';
    b ??= a; // b = '你好”'
    c ??= d // c = '123'

    3.2 Usage Scenarios

    可以在在变量没有被赋值或被赋值为 null 或 undefined 时,将默认值分配给变量
  4. epilogue

这些运算符在处理可能为 null 或 undefined 的值时非常有用,可以简化代码并提高可读性。
然而,需要注意的是,它们是在 ECMAScript 2020 标准中引入的,因此在旧版本的 JavaScript 中
可能不被支持。

a4b73ed1b7f060c80bb3153e75b7384e.jpeg

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/132574134