ES new proposal: double question mark operator

Abstract: A simple and practical new features.

This article is mainly about Gabriel Isenberg ES written proposal "Nullish Coalescing is only valid for JavaScript" . It proposes ??replacing ||the operator, and provides a default value. Here this first phase is called the proposal a double question mark operator , if you have a good name for welcome message discussed.

1 Overview

Double question mark ??operator with ||a similar, if the value of a given variable nullor undefinedjust use the default values by double question mark, otherwise the value of this variable.

as follows:

    > undefined ?? 'default'
    'default'
    > null ?? 'default'
    'default'
    > false ?? 'default'
    false
    > '' ?? 'default'
    ''
    > 0 ?? 'default'
    0

2. Early operation symbol ||

Directly to an example to demonstrate what ||operations, the following two equations are equivalent:

    a || b
    a ? a : b

If you aare truthy value is returned a, otherwise b.

This makes the use ||to specify a default value is possible, if the actual value is false, it will use the default values:

    const result = actualValue || defaultValue;
    function getTitle(fileDesc) {
      return fileDesc.title || '(Untitled)';
    }
    const files = [
      {path: 'index.html', title: 'Home'},
      {path: 'tmp.html'},
    ];
    assert.deepEqual(
      files.map(f => getTitle(f)),
      ['Home', '(Untitled)']);

Please note that basically only in the actual value undefinedor to nullonly use the default value, which is effective since undefinedand nullare false (false value) of:

    > undefined || 'default'
    'default'
    > null || 'default'
    'default'

Unfortunately, if the actual value is other imaginary value, will use the default values:

    > false || 'default'
    'default'
    > '' || 'default'
    'default'
    > 0 || 'default'
    'default'

Therefore, this getTitle()does not always work properly:

    assert.equal(
      getTitle({path: 'empty.html', title: ''}),
      '(Untitled)');

3. double question mark operator to resolve the problem of calculation ||

??Is mainly used to solve ||some of the problems of operating symbols, the following two expressions are equivalent:

    a ?? b
    a !== undefined && a !== null ? a : b

The default value is provided by:

    const result = actualValue ?? defaultValue;

For undefinedand null, ??the working principle of the operator ||operators the same

    > undefined ?? 'default'
    'default'
    > null ?? 'default'
    'default'

In addition to undefinedand nullother dummy value, ??it does not return to the default value.

    > false ?? 'default'
    false
    > '' ?? 'default'
    ''
    > 0 ?? 'default'
    0

Use ??to rewrite getTitle():

    function getTitle(fileDesc) {
      return fileDesc.title ?? '(Untitled)';
    }

Now use fileDescto call it, it .titleis an empty string, it can still work as in line with our expectations:

    assert.equal(
      getTitle({path: 'empty.html', title: ''}),
      '');

3.1 by deconstructing given defaults

Except ??to getTitleadd default values, it may be given by way of deconstruction Default:

    function getTitle({title = '(Untitled)'}) {
      return title;
    }

3.2 Actual operation example of using symbols ??

As a practical example, we use ??to simplify the following functions.

    function countMatches(regex, str) {
      if (!regex.global) {
        throw new Error('Regular expression must have flag /g: ' + regex);
      }
      const matchResult = str.match(regex); // null or Array
      if (matchResult === null) {
        return 0;
      } else {
        return matchResult.length;
      }
    }
    
    assert.equal(
      countMatches(/a/g, 'ababa'), 3);
    assert.equal(
      countMatches(/b/g, 'ababa'), 2);
    assert.equal(
      countMatches(/x/g, 'ababa'), 0);
    
    // Flag /g is missing
    assert.throws(
      () => countMatches(/a/, 'ababa'), Error);

Using ??the operation symbols simplified as follows:

    function countMatches(regex, str) {
      if (!regex.global) {
        throw new Error('Regular expression must have flag /g: ' + regex);
      }
      return (str.match(regex) ?? []).length;
    }

3.3 pairs of question marks (??) with an optional operator chain (?)

Double question mark ( ??) was proposed to supplement optional chain ( ?), take a look at the scene two brothers used in combination (row A):

    const persons = [
      {
        surname: 'Zoe',
        address: {
          street: {
            name: 'Sesame Street',
            number: '123',
          },
        },
      },
      {
        surname: 'Mariner',
      },
      {
        surname: 'Carmen',
        address: {
        },
      },
    ];
    
    const streetNames = persons.map(
      p => p.address?.street?.name ?? '(no name)'); // (A)
    assert.deepEqual(
      streetNames, ['Sesame Street', '(no name)', '(no name)']
    );

4. Compatibility

By table ECMAScript Next compatibility view ??support cases.

After the code is deployed may exist BUG can not know in real time, and afterwards in order to solve these BUG, we spent a lot of time debugging log, here for everyone to recommend a way BUG easy to use monitoring tools Fundebug .

About Fundebug

Fundebug focus on JavaScript, applets micro-channel, micro-channel games, Alipay small program, React Native, Node.js and Java applications in real-time online monitoring BUG. Since 2016, two-eleven formally launched, Fundebug handled a total of 2 billion + error event, paying customers have Sunshine Insurance, walnut programming, lychee FM, head of the 1-to-1, micro pulse, the Youth League and many other community brands. Welcome to Free Trial !

Guess you like

Origin www.cnblogs.com/fundebug/p/javascript-nullish-coalescing.html