Fwd: ||= is much needed?
Rick Waldron
waldron.rick at gmail.com
Tue Jun 12 19:10:21 PDT 2012
This message seems to have disappeared from the archive and since I
referred to it in
http://wiki.ecmascript.org/doku.php?id=strawman:default_operator I wanted
to make sure a record existed.
Rick
---------- Forwarded message ----------
From: Ryan Florence <rpflorence at gmail.com>
Date: Tue, Jun 12, 2012 at 11:45 AM
Subject: Re: ||= is much needed?
To: Rick Waldron <waldron.rick at gmail.com>
Cc: David Bruant <bruant.d at gmail.com>, es-discuss at mozilla.org
I use ||= very regularly in ruby and coffeescript, both of which have
default arguments.
I definitely agree that default arguments are a decent alternative. I
> can't recall examples where it wouldn't be enough. Do you have use cases
> where you would use ||= and default argument values couldn't be used?
>
Its super handy for caching and late/dynamic initialization of object
properties.
var events = {
_callbacks: {},
on: function (topic, callback) {
(this._callbacks[topic] ||= []).push(callback);
...
},
...
};
It's also useful for settings object defaults, especially for expensive
settings that you don't want to calculate in some `defaults` object that is
merged into the settings.
function ajaxWithError (settings) {
settings.method ||= 'POST';
settings.elementPosition ||= this._getElementPositions();
settings.somethingWithInitialization ||= (function(){
var thing = new Thing();
thing.foo = settings.foo;
return thing;
})();
...
};
The ||= (function(){})() should remind any rubyist of `||= begin ... end`
which is beloved by many.
So yeah, I think its really useful outside of default arguments.
- Ryan Florence
On Jun 12, 2012, at 9:06 AM, Rick Waldron wrote:
ahah, I asked the same question very recently [1]. Answer by Brendan Eich
> [2].
> I definitely agree that default arguments are a decent alternative. I
> can't recall examples where it wouldn't be enough. Do you have use cases
> where you would use ||= and default argument values couldn't be used?
>
> David
>
> [1] https://twitter.com/DavidBruant/status/210654806732324864
> [2] https://twitter.com/BrendanEich/status/210750515808706561
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20120612/0da0bac2/attachment.html>
More information about the es-discuss
mailing list