Replace a value if null or undefined in JavaScript

前端 未结 5 1408
刺人心
刺人心 2020-11-30 01:35

I have a requirement to apply the ?? C# operator to JavaScript and I don\'t know how. Consider this in C#:

int i?=null;
int j=i ?? 10;//j is now         


        
5条回答
  •  青春惊慌失措
    2020-11-30 02:10

    ES2020 Answer

    The new Nullish Coalescing Operator, is finally available on JavaScript, though browser support is limited. According to the data from caniuse, only 48.34% of browsers are supported (as of April 2020).

    According to the documentation,

    The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

    const options={
      filters:{
        firstName:'abc'
      } 
    };
    const filter = options.filters[0] ?? '';
    const filter2 = options.filters[1] ?? '';
    

    This will ensure that both of your variables will have a fallback value of '' if filters[0] or filters[1] are null, or undefined.

    Do take note that the nullish coalescing operator does not return the default value for other types of falsy value such as 0 and ''. If you wish to account for all falsy values, you should be using the OR operator ||.

提交回复
热议问题