Cannot return two values in a function. Each return
that you give only returns one value. Thus, if you want to return more than one value for a function, you must use a fixed-size array. In addition, as suggested in the comments by @leofalmeida, it is also possible to use objects.
Returning two values using array:
For example, consider the function below. I want it to return the first parameter and the second parameter:
function twoValues(a, b) {
// Note que estou retornando um array com os dois
// valores que quero retornar.
return [a, b];
}
console.log(twoValues('Luiz', 'Felipe'));
In your case, if you want to return two arrays:
function twoValues(a, b) {
return [a, b];
}
console.log(twoValues([1, 2], [3, 4]));
Returning values using objects:
It is also possible to return an object. This approach is ideal if you want to return multiple values at the same time. An example would be:
function twoValuesViaObject(a, b) {
return {
first: a,
second: b
// ...
}
}
console.log(twoValuesViaObject([1, 2], [3, 4]));
To learn more about the objects, read here.
Operator &&
And in your case, the operator &&
does not work to return two values, since this is not even his function. In that case, he is making a short-circuit evaluation. To learn more about them, see that question.
As you can see, in your example:
var arr1 = [1, 2, 3];
var arr2 = [4, 5];
function mover(arg1,arg2) {
return arg1 && arg2;
}
console.log(mover(arr1, arr2)); // [4, 5]
Only the arr2
is being returned, to the detriment of short-circuit evaluation. Basically, as the arr1
is a value Truthy, the second operand will be returned. To learn more, read the linked question above.
Learn more...
For further information, I recommend reading about the allocation via structuring, that can help work with objects and arrays. ;)
Luiz seeing his example above, if a was an array and b was another array as it would look?
– Marcel Roberto Piesigilli
There is no difference. It is the same thing, since you can have arrays inside arrays (there is no limit to this - at least I do not know). I edited the question by adding another example...
– Luiz Felipe
Just by complementing the answer: you can return an object too, then follows the same rule of the array:
return { primeiro: a, segundo: b }
. The advantage is to be able to name the returns.– leofalmeida
@leofalmeida, de facto! Objects can be very useful in this case if it is necessary to return many values. I can edit the answer by adding this detail? :)
– Luiz Felipe
At ease haha! :)
– leofalmeida
One last question where the hell do you push and pop? I don’t see that application in the market!
– Marcel Roberto Piesigilli
Create another question for this, so we don’t escape the scope of this... :) If this answer helped you, don’t forget to accept it by clicking the check icon ( ) in the upper left corner of the answer.
– Luiz Felipe