Short Functions

Lasse Reichstein reichsteinatwork at gmail.com
Wed May 25 05:30:39 PDT 2011


On Sun, 22 May 2011 02:56:28 +0200, Brendan Eich <brendan at mozilla.com>  
wrote:

> Why is this so bad? JS programmers return, break, and continue from  
> blocks all the time.

Just dawned on me that there is a significant difference.

JS blocks are executed where they are lexically located. If in a loop,  
they are
executed sequentially. You can see their control flow scope (e.g., any  
local try/catch/finally
blocks).

When you make blocks into first-class values (and even throw in  
parameterization), you can
get blocks being re-entered (e.g., being called recursively), and they can  
be called in scope
of a finally that you can't see.

Example (using simple block syntax)

function contains(collection, y) {
    collection.forEach({|x| if (x == y) return true; });
    return false;
}

but if Collection.forEach is, e.g.,:

  function forEach(block) {
     for (var i = 0; i < this.length; i++) {
       try {
         block(this[i]);
       } finally {
	// Always iterate to the end!
         continue;
       }
     }
  }

then what is "obviously" a "local return" in the contains function, isn't  
actually doing what
it's expected to.
In that sense, the block is like a function, and thinking of it as a block  
is likely to
lead to surprises because they lack the statically detectable runtime  
context of blocks.

/L
-- 
Lasse Reichstein - reichsteinatwork at gmail.com


More information about the es-discuss mailing list