Consistency in The Negative Result Values Through Expansion of null's Role

Brendan Eich brendan at mozilla.org
Mon Aug 20 09:41:06 PDT 2012


Andreas Rossberg wrote:
> Hm, I don't see how this example relies on an in-band sentinel. The
> loop condition would work just as well with a comparison to undefined.
> Everything else is regular argument values.

This loop could indeed test

   while ((i = s.indexOf('  ', j)) !== undefined) ...

That is unsightly, overlong, and contrived, but never mind.

What I was trying to get to -- and utterly failed to get to last time -- 
was a use of the -1 return value. Here's what I should have written, a 
"split on single-char string" that does not rely on trailing separator 
(i.e. termination):

var s = "a bbb cccc ddddd"
var i, j = 0;
var a = [];
do {
     i = s.indexOf(' ', j);
     a.push(s.slice(j, i));// j lags i and slice(j, -1) returns tail
} while ((j = i + 1) != 0);
print(a);

This prints

a,bbb,cccc,dddd

Here, using undefined instead of -1 does not work -- you get an iloop 
becanse NaN != 0.

Contrived? Less so than a forced undefined sentinel. This is a 
simplified split that handles the no-separator basis case correctly. 
Similar examples come up from time to time in the real world.

Multiply typed return values for indexOf, charAt and probably others, 
depending on the particulars, can be losing not winning. I'm not going 
to generalize, but I am here to argue against a generalization that I 
thought I read, where OOB return is always "failure" and must be 
signified by a differently-typed sentinel.

I don't believe that leads to the most usable API in general, and it 
also can run afoul of implicit conversions.

/be


More information about the es-discuss mailing list