How best to implement out params in JavaScript?

Nick Heiner picture Nick Heiner · Jul 4, 2010 · Viewed 60.4k times · Source

I'm using Javascript with jQuery. I'd like to implement out params. In C#, it would look something like this:

/*
 * odp      the object to test
 * error    a string that will be filled with the error message if odp is illegal. Undefined otherwise.
 *
 * Returns  true if odp is legal.
 */
bool isLegal(odp, out error);

What is the best way to do something like this in JS? Objects?

function isLegal(odp, errorObj)
{
    // ...
    errorObj.val = "ODP failed test foo";
    return false;
}

Firebug tells me that the above approach would work, but is there a better way?

Answer

Pointy picture Pointy · Jul 4, 2010

The callback approach mentioned by @Felix Kling is probably the best idea, but I've also found that sometimes it's easy to leverage Javascript object literal syntax and just have your function return an object on error:

function mightFail(param) {
  // ...
  return didThisFail ? { error: true, msg: "Did not work" } : realResult;
}

then when you call the function:

var result = mightFail("something");
if (result.error) alert("It failed: " + result.msg);

Not fancy and hardly bulletproof, but certainly it's OK for some simple situations.