Return multiple values from a function using a JSON Object

Quick example of how a function can return multiple values using a JSON object.
Sometimes even a good developer gives a second thought on how to return multiple values from within a function to a script that’s calling the function. Let’s go behind the scenes and very briefly reveal the secrets.

JavaScript Object – JSON object – What is that?
A JSON object has a key-value pair structure. It is this feature that helps store multiple values in multiple corresponding keys within the JSON object. Not only that you can store multiple data types within one JSON object. Let’s see an example,

var json_object = {
  key1: "value1", //stores a string value
  key2: value2, //stores a number data type value
  key3:true //stores a boolean type value
}

Since you can store multiple values within one object so if you return this JSON object variable then you are also returning multiple values at once isn’t it. Let’s see how to do it.

Return a JSON Object

function func1() {
  var myObj = returnValues(2, "string");
  alert("Value1 returned: " + myObj.a);
  alert("Value2 returned: " + myObj.b);
}

function returnValues(value1, value2) {
  var newValue1 = value1 * 2;
  var newValue2 = "returned " + value2
  var return_object = {
    a:newValue1,
    b:newValue2
  };
  return return_object;
}

I have an example code above where the function returnValues() returns a JSON object to the function – func1(). Within func1() I am calling the function returnValues() and passing two parameters – value1 which is a number and value2 which is a string value. Inside returnValues() function I just manipulate the parameters passed to it and create two new values out of it. The two new values (newValue1, newValue2) are then assigned to two keys of our JSON object –  return_object. Finally the JSON object is returned by the function. This way I am passing a number and a string- multiple values and multiple types.
Now within func1() we can access the values passed to it by the accessing the object keys using the DOT operator. This is how to do it.

alert("Value1 returned: " + myObj.a);
alert("Value2 returned: " + myObj.b);

This way you can return as many values as you want.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s