||= is much needed?

Rick Waldron waldron.rick at gmail.com
Tue Jun 12 10:14:53 PDT 2012


On Tue, Jun 12, 2012 at 11:45 AM, Ryan Florence <rpflorence at gmail.com>wrote:

> 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
>
>
Forgive the dogpiling, but these are really excellent real-world use cases
that represent massive pain points in modern JavaScript programming. Thanks
for writing these up Ryan, I've added them to strawman:
http://wiki.ecmascript.org/doku.php?id=strawman:default_operator

Rick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20120612/f7fe3e43/attachment-0001.html>


More information about the es-discuss mailing list