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?
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.
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.
4 Ways to Declare a JavaScript Variable:Using var. Using let. Using const. Using nothing.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With