How to return values in javascript
Solution 1:
You can return an array, an object literal, or an object of a type you created that encapsulates the returned values.
Then you can pass in the array, object literal, or custom object into a method to disseminate the values.
Object example:
function myFunction(value1,value2,value3)
{
var returnedObject = {};
returnedObject["value1"] = value1;
returnedObject["value2"] = value2;
return returnedObject;
}
var returnValue = myFunction("1",value2,value3);
if(returnValue.value1 && returnValue.value2)
{
//Do some stuff
}
Array example:
function myFunction(value1,value2,value3)
{
var returnedArray = [];
returnedArray.push(value1);
returnedArray.push(value2);
return returnedArray;
}
var returnValue = myFunction("1",value2,value3);
if(returnValue[0] && returnValue[1])
{
//Do some stuff
}
Custom Object:
function myFunction(value1,value2,value3)
{
var valueHolder = new ValueHolder(value1, value2);
return valueHolder;
}
var returnValue = myFunction("1",value2,value3);
// hypothetical method that you could build to create an easier to read conditional
// (might not apply to your situation)
if(returnValue.valid())
{
//Do some stuff
}
I would avoid the array method because you would have to access the values via indices rather than named object properties.
Solution 2:
Javascript is duck typed, so you can create a small structure.
function myFunction(value1,value2,value3)
{
var myObject = new Object();
myObject.value2 = somevalue2;
myObject.value3 = somevalue3;
return myObject;
}
var value = myFunction("1",value2,value3);
if(value.value2 && value.value3)
{
//Do some stuff
}
Solution 3:
function myFunction(value1,value2,value3)
{
return {val2: value2, val3: value3};
}
Solution 4:
It's difficult to tell what you're actually trying to do and if this is what you really need but you might also use a callback:
function myFunction(value1,callback)
{
//Do stuff and
if(typeof callback == 'function'){
callback(somevalue2,somevalue3);
}
}
myFunction("1", function(value2, value3){
if(value2 && value3)
{
//Do some stuff
}
});