JavaScript functions, named parameters.

JavaScript does not support named parameters. For example following will not work in JS:

  var something = foo( one: 1, two: "2" );

As a workaround people use functions that accept single parameter – object reference:

  var something = foo( { one: 1, two: "2" } );

but I think such notation is not good aesthetically speaking …

Problem is that classic JS supports only one form of function call :

  ref '(' list-of-values ')'

In TIScript/Sciter I decided to “fix” this by introducing second form of function call – call of function with passing object literal:

  ref object-literal

Where object-literal is a standard (for JS) object literal: '{' list-of-name-value-pairs '}'.

Thus example above can be rewritten as

  var something = foo { one: 1, two: 2 };

foo is a function here that accepts single parameter – parameter-object:

  function foo( prm ) { return prm.one + prm.two; }

Practical example:
When I need to create DOM object dynamically I can write now something like this:

          tab = Element.create { tag: "option", text: label, value: filename };

that is a bit shorter than:

          tab = new Element("option");
          tab.text = label;
          tab.attributes["value"] = filename;

To be able to create DOM elements this way I’ve extended Element class (DOM element in Sciter) by following function:

/*
  create element by definition (def)
  Example:

  var el = Element.create { 
    tag:"p", 
    text:"hello", class:"info", id:"id1" 
  };
*/
function Element.create(def)
{
  var tag = def.tag; if(!tag) throw "No tag given!";
  var text = def.text || ""; 
  var el = new Element(tag, text);
  for (var k in def)
  {
    if( k == #tag || k == #text ) continue;
    if( k == #children )
    {
      var children = def.children;
      if( typeof children != #array) throw "'children' is not an array!";
      for (var c in children )
        el.insert( Element.create(c) );
      continue;
    }
    // others are just attributes
    el.attributes[k] = def[k];
  }
  return el;
}

and this is it.

2 Replies to “JavaScript functions, named parameters.”

  1. Ruby’s solution for the same problem seems more natural for me. It just treats
    fun(a, b, c=>d, e=>f)
    as
    fun(a, b, {c=>d, e=>f})
    the function having three parameters with last one being Hash.

  2. Yep, that is probably more convenient but such a solution is hard to define in terms of formal grammar.

    And I think that construction

    fun { a:b, c:d, e:f }
    

    is a bit more obvious to what is going on under the hood.
    But this is probably just a matter of personal preferences.

    In any case proposed function-with-an-object call fits in existing JavaScript grammar flawlessly.

Comments are closed.