Assignment to method invocation result

Jussi Kalliokoski jussi.kalliokoski at gmail.com
Thu May 15 04:27:10 PDT 2014


Throughout my history with JS (and pretty much every programming language
I've used) I've always found one thing really awkward: reassigning a
variable to the result of its method.

Say you have code like this:

var foo = function (options) {
  var string = something();

  if ( options.stripWhiteSpace ) {
    string = string.trim();
  }

  // do something else here...
};

The same thing applies to pretty much all methods that return a modified
version of the same type of the variable, e.g. replace, filter, map,
concat, etc., you name it.

As a comparison let's say we had Number#add() and no operators for the add
method:

var bar = function (firstNumber, secondNumber) {
  var thirdNumber = 5;
  if ( firstNumber > 0 ) {
    secondNumber = secondNumber.add(thirdNumber);
  }
  firstNumber = firstNumber.add(secondNumber);
};

whereas with the operators we have the convenience of combining the
operator with the assignment to avoid typing the variable name twice:

var bar = function (firstNumber, secondNumber) {
  var thirdNumber = 5;
  if ( firstNumber > 0 ) {
    secondNumber += thirdNumber;
  }
  firstNumber += secondNumber;
};

I don't really know what would be a good solution for this problem, hence I
wanted to share this here if we can figure out a nicer way to do these
kinds of things. The best I can think of is some syntax like this:

var foo = function (options) {
  var string = something();

  if ( options.stripWhiteSpace ) {
    string = .trim();
  }

  // do something else here...
};

so basically the operator would a combination of assignment followed by
property access dot, then the method name and invocation. This could also
allow plain property access so you could for example say `foo = .first` or
something. The reason I don't like this syntax is that it might be
conflicting with other some ideas thrown around to replace `with`, e.g.:

using (foo) {
  .remove(x);
  var x = .size;
}

- Jussi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20140515/9a8673ca/attachment-0001.html>


More information about the es-discuss mailing list