Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How best to implement out params in JavaScript?

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?

like image 432
Nick Heiner Avatar asked Jul 04 '10 18:07

Nick Heiner


People also ask

How parameters are passed in JavaScript?

The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value.

How can I pass multiple parameters in JavaScript function?

When you call a function in JavaScript, you can pass in any number of arguments, regardless of what the function declaration specifies. There is no function parameter limit. In the above function, if we pass any number of arguments, the result is always the same because it will take the first two parameters only.

What are the 4 ways to declare a JavaScript variable?

4 Ways to Declare a JavaScript Variable:Using var. Using let. Using const. Using nothing.

Why do we use out parameter?

It is generally used when a method returns multiple values. Important Points: It is similar to ref keyword. But the main difference between ref and out keyword is that ref needs that the variable must be initialized before it passed to the method.


1 Answers

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.

like image 74
Pointy Avatar answered Sep 30 '22 09:09

Pointy