Returng Two or More Values from a Javascript Function

Guest Posts Paolo Nikko Nuñal

In our previous tutorial, we have manage to return functions with a value, in this segment, you are going to learn on how you can return two variables inside a function. This is the most common problem that many developers have been trying to solve, this is possible and can even make your code even smaller. You can also return two values or more using variables as objects. Or return specific variables only.

The secret lies on using Objects.

Code


<script>
     var num1 = 5;
     var num2 = 3;

     data =  addminusNumbers(num1, num2);
     alert("The sum of "+num1+" and "+num2+" is: " +data.addends);
     alert("The difference of "+num1+" and "+num2+" is :" +data.difference);
     function addminusNumbers(num1, num2)
     {
         x = num1 + num2;
         y = num1 - num2;
         return{ addends: x, difference: y}
     }
</script>


Base on the code above, we have treated the values addends and difference as objects. The variable x contains the total of the two numbers in which it is stored in the "addends" object. The y value contains the difference of the two numbers is stored on the "difference" object.  When you want to return more than two values, always remember to separate them with a comma. The same as you did when dealing with objects.

When invoking the addminusNumbers() we have also created a data variable in which it contains the result of that method. Since it returns two object properties we can also call each property name as seen in the example above. To call the addends property name, all you have to do is place a dot, after the variable "data".

data.addends - calls the propertyName addends that has the total of the two numbers.

data.difference - calls the propertyName difference that has the difference of the two numbers.