Skip to content

Instantly share code, notes, and snippets.

@ephys
Last active September 24, 2016 14:37
Show Gist options
  • Save ephys/39d3c60eb92c81163499bf57c8c08b15 to your computer and use it in GitHub Desktop.
Save ephys/39d3c60eb92c81163499bf57c8c08b15 to your computer and use it in GitHub Desktop.
EcmaScript - Undefined Coalesce Operator / Default Operator Proposal

EcmaScript Default Operator / Undefined Coalesce Operator

Overview and Motivation

EcmaScript 2015 introduced a new mechanism that enabled developers to define the default values of their function parameters.
Though it is powerful, that mechanism often cannot be used when setting the default values of the properties of received object arguments without destructuring them.

One such case would be a method having to pass the argument to another method :*

class A {
    init(config) {
        // handle config options speciifc to A
    }
}

class B extends A {
    init(config) { // destructuring here just isn't an option.
        super.init(config);

        // handle config options specific to B
    }
}

* Could possibly be solved by this

As a result, developers tend to use the logical OR (||) operator to assign a default value to these object arguments. Resulting in the following:

//...
init(config) {
    super.init(config);
    
    this.timeout = config.timeout || 4000; 
}
//...

Very popular tools and libraries make use of the operator in that way

That operator works fine for most use cases but silently fails if a falsy value is a valid input.
In order to avoid introducing bugs, developers should check that the value is undefined rather than falsy. Unfortunately, doing so is much more verbose. Which is why developers still use the error-prone || operator to assign default values to this day.

Proposed solution

Introduce a new operator, ??, whose behavior is the following

DefaultExpression: LogicalORExpression ?? AssignmentExpression

  1. Let lref be the result of evaluating LogicalORExpression.
  2. Let lval be ?GetValue(lref).
  3. If lval is not undefined, return lval.
  4. Let rref be the result of evaluating AssignmentExpression.
  5. Return ?GetValue(rref).

TODO ??= operator.

Debatable topics

Should it return the second hand operand if the first-hand operand is null as well as undefined ?

Default operator, works similarly to default parameters.

Why the choice of ?? as the operator ?

  • Pro:
    • It is similar to the null coalesce operator in other languages, closely resembles the current operator used to assign default values.
  • Con:
    • It does not have the exact same behavior as the other languages. This could make this operator slightly confusing to newcomers.

Previous discussions related to this proposal

Formal, 4 years old, strawman
ESDiscuss thread about above strawman
Null coalesce operator ESDiscuss thread

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment