return multiple values from a function javascript code example
Example 1: can you return 2 values in javascript object
function friends(){
var names = {
closeCircle: ['bebo','eli','matthew'],
outerCircle:['vierie','nate','james','george'],
};
return [names.closeCircle[0], names.closeCircle[2]]
//returns bebo and matthew
}
Example 2: javascript return multiple values from a function
//function that returns multiple values
function getTopTwoColors() {
return ["blue", "pink"];
}
var topTwoColors=getTopTwoColors();
var firstValue=topTwoColors[0]; //get first return value
var secondValue=topTwoColors[1]; //get second return value
Example 3: return multiple values in javascript
function getNames() {
// get names from the database or API
let firstName = 'John',
lastName = 'Doe';
// return values
return {
firstName,
lastName
};
}
Example 4: return two arrays javascript
this.runThisFunctionOnCall = function(){
var array1 = [11,12,13,14,15];
var array2 = [21,22,23,24,25];
var array3 = [31,32,33,34,35];
return [
array1,
array2,
array3
];
}
Example 5: javascript function multiple return
function doubleEachElement(num1, num2) {
return [num1 * 2, num2 * 2];
}
const [a, b] = doubleEachElement(68, 100);