Skip to content

How to return multiple values from a JavaScript function?

Learn how to return multiple values from a JavaScript function. No, I don’t use an Array to return multiple values. Using an array to hold many values, return the array and get the values one by one is an age old method.

You can just enclose your values inside {} and return it. In the caller function, you can use {} and retrieve the values.

function getSumAvg(a,b) {

	let sum = a + b;
	let avg = (a + b) / 2;
	return {sum, avg};	
  
}


function mathOps(a,b) {

 const {sum, avg} = getSumAvg(a,b);
 console.log("Sum = " + sum);
 console.log("Avg = " + avg);
	
}


mathOps(3,5);
//Sum = 8
//Avg = 4

When you retrieve the values, it has to be in the same order as the returned order. Otherwise it won’t work!

See also  How to get client's IP address using JavaScript?
, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.