How can i return multiple values from the function in javascript. And how to use that.??
Asked
Active
Viewed 1.7k times
3
-
1Return an Object, instead. – StackSlave Oct 24 '17 at 07:13
2 Answers
6
Functions by definition can only return one value. However, you can pack your values in an array or an object:
function greeting(){
return {
name: "Andy",
message: "Hello world"
};
}

Derek 朕會功夫
- 92,235
- 44
- 185
- 247
6
You can't do that.
But, you can return an array
or an object which contains your values.
function doSomething(a,b){
return [a,b];
//return {a,b};
}
console.log(doSomething(1,2));
If you want to return many values you can use destructing
operator in order to find out all the values.
function doSomething(a,b,c,d,e,f){
return {a,b,c,d,e,f};
}
let {a,b,c,d,e,f}=doSomething(1,2,3,4,5,6);
console.log(a,b,c,d,e,f);

Mihai Alexandru-Ionut
- 47,092
- 13
- 101
- 128
-
What the method return type would be if we wanted to see it in the signature ? – Stephane Apr 01 '22 at 13:31