JavaScript function return multiple values | Use Array Example

Can function return multiple values in JavaScript?

No, the JS function could not return multiple value returns but it could return an array containing multiple values or as properties of an object.

Note: JavaScript functions can return only single value.

JavaScript function return multiple values Example code

Let’s see HTML example code for How to Return multiple values in JavaScript.

Return as Array

function getValues() {
    return [getFirstValue(), getSecondValue()];
}

Get the values

var values = getValues();
var first = values[0];
var second = values[1];

Complete example code:

<!DOCTYPE html>
<html>
<body>
	<script> 
		function nameFunc() {

			let firstName = "John";
			let lastName = "Dow";

			return [firstName, lastName];
		}

		let names = nameFunc();
		console.log(names);

		//get single values
		console.log(names[0]);
		console.log(names[1]);

	</script> 

</body>
</html>

Output:

JavaScript function return multiple values

Return as object

<!DOCTYPE html>
<html>
<body>
	<script> 
		function getNames() {

			let firstName = 'John';
			let lastName = 'Deep';


			return { firstName, lastName};
		}

		let names = getNames();

		let firstName = names.firstName,
		lastName = names.lastName;

		console.log(names);

	</script> 

</body>
</html>

Output:

JavaScript function return multiple values Example

Object with labels

If you want to put “labels” on each of the returned values (easier to maintain), you can return an object:

<!DOCTYPE html>
<html>
<body>
	<script> 
		function getNames() {

			let firstName = 'John';
			let lastName = 'Deep';


			return { first: firstName, second: lastName};
		}

		let names = getNames();

		console.log(names);

		// access them:
		var first = names.first;
		var second = names.second;

		console.log(first,second);

	</script> 

</body>
</html>

Output:

labeled object Return multiple values in JavaScript

Do comment if you any doubts and suggestions on this JS function topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

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