Return Two Values to Function in ES6

Very cool (nerd-cool, that is) discovery of the day. A quick Google led me to Dr. Axel Rauschmayer’s site, where I learned how to return multiple values to a function in ES6 (JavaScript).

Use Case: Check to see selected value matches one of two acceptable options out of a larger list. If so, continue. Then, if that selection matches a certain value, apply a condition:

  • If value is “Raptor” or “Viper,” then go down the path.
  • If value is “Raptor,” do this special thing, then continue down the path.
  • If value is not “Raptor” or “Viper,” exit

Here’s the code block that kicks off the process. It’s initiated by calling funFunction:

const isSpaceship = (ele) => {	
	if (ele) {
		console.log('Happy path. Ele exists.');
		let selectedOption = ele.options[ele.selectedIndex].text;
		if ( selectedOption == 'Raptor' || selectedOption == 'Viper') return { ready: true, value: selectedOption };
	return { ready: false };		
const funFunction = () => {
	const documentStatusElement = document.getElementById('vehicle-selector');	
	let { ready, value } = isSpaceship(documentStatusElement);
	switch (value) {
		case 'Raptor':
			console.log(`value: ${value}. Plan to do The Special. But first do this thing.`);
		case 'Viper':
			console.log(`value: ${value}. Plan to do The Special. But first do that thing.`);
			console.log(`value: ${value}. Do this other thing.`);
	ready == true 
		? console.log(`ready: ${ready}. Do The Special.`)		
		: console.log(`ready: ${ready}. Do this other thing.`);	

When funFunction is called, it checks the value of #vehicle-selection. If the value selected by the user is either “Raptor” or “Viper,” the isSpaceCraft function returns “true” AND the value as ready and value, respectively.

If ready is true, funFunction then returns value to the console. In place of the ternary, you can build out the subsequent process flows.

Special thanks to Dr. Axel and his article Multiple return values in ECMAScript 6.

Also published on

Related Articles

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x