Problem
I have the issue where I need to pass multiple variables from one function to another. And both variables that need to be passed come from the same initial function.
I can pass one variable between objects ok (not in an ojbect), but passing multiple variables doesn't seem to work when I try and pass them as an object, which seemed to be the closest source for what I'm after here...
What works
Here's the snippet of the code that is working for passing a single variable from one function to another...
function processFruits() {
//runs the getFruits function first to obtain the variable for processing in the next function
getFruits();
//runs the retrieveInfo function using the fruitType variable from the initial function
retrieveInfo(getFruits(fruitType));
}
function getFruits() {
//does something which get the fruit type and number of fruits
fruitType = 'bananas';
fruitNumber = matches[0];
return fruitType;
}
function retrieveInfo(b) {
console.log("The fruit is: " b);
}
//Returns 'The fruit is: bananas'
What doesn't work
Here's the snippet of code that isn't working:
function processFruits() {
//runs the getFruits function first to obtain the variables for processing in the next function
getFruits();
//runs the retrieveInfo function and tries to pass the variables from getFruits as variables within an object
retrieveInfo(getFruits.fruitType, getFruits.fruitNumber);
}
function getFruits() {
//does something which get the fruit type and number of fruits
let fruitType = 'bananas',
fruitNumber = matches[0]; //let's say this is returning the number '5'
return { fruitType, fruitNumber };
}
function retrieveInfo(b, c) {
console.log("The fruit is: " b);
console.log("The number of desired fruit is: " c);
}
This returns 'The fruit is: undefined' AND 'The number of desired fruit is: undefined'...
Whereas, it needs to return 'The fruit is: bananas' AND 'The number of desired fruit is: 5'...
To reiterate, the script just needs to be able to pass multiple variables from one function to another for the snippet above, so it ends up giving the desired outcome...
Thanks in advance
CodePudding user response:
You need to access the properties of the return value of the function. Destructuring assignment is convenient for this.
function processFruits() {
let {fruitType, fruitNumber} = getFruits();
retrieveInfo(fruitType, fruitNumber);
}
function getFruits() {
let fruitType = 'bananas',
fruitNumber = 1;
return { fruitType, fruitNumber };
}
function retrieveInfo(b, c) {
console.log("The fruit is: " b);
console.log("The number of desired fruit is: " c);
}
processFruits();