Is it possible to check for null inline in javascript?

前端 未结 7 2297
孤街浪徒
孤街浪徒 2020-12-15 18:27

I have a function which parses the address components of the Google Maps API JSON and then returns the city / locality / route name.

The getAddre

7条回答
  •  暖寄归人
    2020-12-15 19:08

    • There is no "null-safe navigation operator" in Javascript (EcmaScript 5 or 6), like ?. in C#, Angular templates, etc. (also sometimes called Elvis operator, when written ?:) , at least yet, unfortunately.

    • You can test for null and return some dependent expression in a single line with the ternary operator ?:, as already given in other answers :

      (use === null to check only for nulls values, and == null to check for null and undefined)

      console.log(myVar == null ? myVar.myProp : 'fallBackValue');
      
    • in some cases, like yours, when your variable is supposed to hold an object, you can simply use the fact that any object is truthy whereas null and undefined are falsy values :

      if (myVar) 
          console.log(myVar.myProp)
      else
          console.log('fallbackValue')
      

      You can test for falsy values by coalescing to boolean with !! and make this inline :

      console.log(!!myVar ? myVar.myProp : 'fallbackValue');
      

      Be very careful though with this "falsy test", for if your variable is 0, '', or NaN, then it is falsy as well, even though it is not null/undefined.

提交回复
热议问题