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

Brendan Eich brendan at mozilla.org
Thu Aug 16 14:24:36 PDT 2012


Norbert Lindenberg wrote:
> On Aug 15, 2012, at 15:35 , Rick Waldron wrote:
>
>> On Wed, Aug 15, 2012 at 6:02 PM, Erik Reppen<erik.reppen at gmail.com>  wrote:
>>
>>> * 'wombat'.charAt(20); //returns an empty string, but that's a concrete value whereas 'wombat'[20] returns undefined
>>>
>> For the same reason indexOf always returns a number, charAt always returns a string.
>>
>> "wombat"[20] will dereference the string at an index that doesn't exist, which means it's undefined.
>
> I think undefined would have been a fine return value for 'wombat'.charAt(20) - you asked for something that's not there. The expected return value in the "it's there" case is a one-code-unit string, so an empty string doesn't meet expectations anyway.

But you are requiring all clients who take the in-band return value to 
be string and concatenate it, e.g., to check and avoid cat'ing "undefined".

Having a monotyped return value is common in scripting languages and it 
avoids requiring callers to write a refutable match. Irrefutable FTW again!

>>> * NaN - It can tell you a lot about what kind of thing went wrong but given it's not-equal-to-itself nature it can be a nasty return value when unexpected. For instance, 'wombat'.charCodeAt(20) returns NaN. How does this makes sense in the context of JavaScript? Yes, I'm trying to get a number but from what I would assume (in complete ignorance of unicode evaluation at the lower level) is some sort of look-up table. I'm not trying to divide 'a' by 2, parseInt('a') or get the square root of a negative number.
>
> In this case NaN is clearly wrong, because what the caller expects is a code unit, an integer between 0 and 0xFFFF. You have to check for NaN just like you have to check for undefined, but undefined would have been the normal JavaScript result for "nothing there".

You don't always have to check for NaN, again. Code that is testing for 
a certain code unit using === or even == (because the monotyped return 
value ensures number) will get guaranteed mismatch with NaN.

It's true that undefined converts ToNumber resulting in NaN, so this 
case is a bit better than the first one -- no string concatenation issue.

> It's too late to fix charCodeAt, but for the new codePointAt I'm proposing undefined as the "nothing there" result.
> http://norbertlindenberg.com/2012/05/ecmascript-supplementary-characters/index.html#String

Why is undefined better than NaN? Aesthetics about "nothing there" are 
not really relevant. You should make a case based on common code 
patterns and what happens if there is no extra out-of-band return value 
check (which there need not be in many cases, e.g. === or ==).

/be


More information about the es-discuss mailing list