Existential operator (was: ||= is much needed?)

Brendan Eich brendan at mozilla.org
Wed Jun 20 10:45:53 PDT 2012


Allen Wirfs-Brock wrote:
> I was hypothesizing that Brendan's semantics would seldom be the 
> programer's intent for person?.getName() . If an exception was 
> acceptable, why wouldn't you just say:

Because it's rare to have a maybe-method called on a maybe-object, based 
on CoffeeScript experience and design. Please don't personalize this -- 
I wrote the strawman to capture what CoffeeScript has user-tested. Any 
bugs are mine, but they're also not (necessarily) intended.

Clearly I did not push the indefinite-null/undefined-soak semantics. 
That's in CoffeeScript. However, it does not suppress throwing on a call 
of a non-callable:

$ cat /tmp/y.coffee
person = {}
person?.getName()

$ ./bin/coffee -p /tmp/y.coffee
(function() {
   var person;

   person = {};

   if (person != null) {
     person.getName();
   }

}).call(this);

$ ./bin/coffee /tmp/y.coffee
TypeError: Object #<Object> has no method 'getName'
     at Object.<anonymous> (/private/tmp/y.coffee:7:12)
     at Object.<anonymous> (/private/tmp/y.coffee:10:4)
     at Module._compile (module.js:432:26)
     at Object.run 
(/Users/brendaneich/Hacking/coffee-script/lib/coffee-script/coffee-script.js:79:25)
     at 
/Users/brendaneich/Hacking/coffee-script/lib/coffee-script/command.js:175:29
     at 
/Users/brendaneich/Hacking/coffee-script/lib/coffee-script/command.js:150:18
     at [object Object].<anonymous> (fs.js:114:5)
     at [object Object].emit (events.js:64:17)
     at afterRead (fs.js:1081:12)
     at Object.wrapper [as oncomplete] (fs.js:252:17)

Let's look at what CoffeeScript requires to avoid this exception:

$ cat /tmp/z.coffee
person = {}
person?.getName?()

$ ./bin/coffee -p /tmp/z.coffee
(function() {
   var person;

   person = {};

   if (person != null) {
     if (typeof person.getName === "function") {
       person.getName();
     }
   }

}).call(this);

$ ./bin/coffee /tmp/z.coffee && echo "no throw"
no throw

Again, I do not see the point in gratuitously differing from 
CoffeeScript without reason. One might argue that since we cannot use ?( 
as CS does, we should make ?. soak up call TypeErrors. Could be, but I 
didn't propose anything for call yet and this discussion seems worth 
beating into the ground a bit more before I do :-).

/be


More information about the es-discuss mailing list