'void' as a value

Andrew Fedoniouk news at terrainformatica.com
Sun Sep 8 11:24:46 PDT 2013


Consider this function:

function foo( t ) {
  if( t ) return undefined;
  // no return here, sic!
}

As you see it returns 'undefined' when 't' gets true.
When 't' is false it also returns the same 'undefined'.

But conceptually these are two different return cases/values:
  'undefined' and 'nothing' (or 'void').

Allowing functions to return 'void' values will give us opportunity
to use ordinary functions as iterators without need of separate Iterator entity.

Consider this Range implementation:

function Range(low, high){
  var index = low;
  return function() { if( index < high )  return index++;  }
}

and its use:

for(var i in Range(0,10) )
  ...

Internal implementation of for..in is calling the function in each iteration
and stops when the function will return 'void'.

To keep backward compatibility the 'void' value shall not be assignable,
so after this:

function returnsNothing() { return; }

var retval = returnsNothing();

the retval will still contain 'undefined' value.

And expression:
   returnsNothing() === undefined
yields 'true'.

Therefore the 'void' value is mostly for internal use.

But in some cases user space code may also be interested in
checking returns for 'void' values. In this case we can provide
checkVoid(probe,valOrCallback) primitive:

var result = checkVoid( returnsNothing(), "nothing" );

in this case the result will get "nothing" value. If valOrCallback is a function
then it will be invoked to indicate 'void' value:

var gotNothing = false;
var result = checkVoid( returnsNothing(), function() { gotNothing = true } );

My pardon if something similar to this was already discussed by the group.

I am using this mechanism in my TIScript and found it quite useful and effective
for implementing iterator cases - at least no need for exceptions as shown here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators

-- 
Andrew Fedoniouk.

http://terrainformatica.com


More information about the es-discuss mailing list