Is there a standard function to check for null, undefined, or blank variables in JavaScript?

前端 未结 30 3574
眼角桃花
眼角桃花 2020-11-21 23:37

Is there a universal JavaScript function that checks that a variable has a value and ensures that it\'s not undefined or null? I\'ve got this code,

30条回答
  •  你的背包
    2020-11-22 00:17

    The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null.

    let customer = {
      name: "Carl",
      details: {
        age: 82,
        location: "Paradise Falls" // detailed address is unknown
      }
    };
    let customerCity = customer.details?.address?.city;
    

    The nullish coalescing operator may be used after optional chaining in order to build a default value when none was found:

    let customer = {
      name: "Carl",
      details: { age: 82 }
    };
    const customerCity = customer?.city ?? "Unknown city";
    console.log(customerCity); // Unknown city
    

提交回复
热议问题