Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save emfluenceindia/60db3dbd38645fa0c848dc576b15b0f1 to your computer and use it in GitHub Desktop.
Save emfluenceindia/60db3dbd38645fa0c848dc576b15b0f1 to your computer and use it in GitHub Desktop.
ES6 example of handling Multiple Return Value from a function and application of Destructuring
/**
A simple example showing how Multiple return values are handled in ES6 and then further modified it using Object Destructuring.
I have used ES6 function syntax and ES6 template literal approach in this example.
*/
// Function to return multiple values (properties) bundled inside a JavaScript object.
const compoundInterestCalculator = ( amount, roi, compoundingTimesPeryear, years ) => {
const maturityAmount = (amount * Math.pow((1 + (roi/(compoundingTimesPeryear*100))), (compoundingTimesPeryear*years)));
const objOutput = {
depositAmount: amount,
rateOfInterest: roi,
noOfYears: years,
interestAcumulated: maturityAmount - amount,
maturityValue: maturityAmount
}
return objOutput;
}
// Call the function to get the object with multiple properties.
const calculated = compoundInterestCalculator( 150000, 6.5, 1, 5 );
//Show the complete object - the return value
console.log(calculated);
// Destructure return value
const {maturityValue, interestAcumulated} = calculated;
// Output from Destrured object
console.log(`Maturity value: ${maturityValue.toFixed(2)}.\nInterest gained: ${interestAcumulated.toFixed(2)}`);
/**
NOTE:
Rather than storing function's return value in a variable we can Destrucure it immediately and use in output like below:
const {maturityValue, interestAcumulated} = compoundInterestCalculator( 100000, 6.5, 1, 5 );
console.log(`Maturity value: ${maturityValue.toFixed(2)}.\nInterest gained: ${interestAcumulated.toFixed(2)}`);
*/
/**
Output:
--------------------
*/
{
depositAmount: 150000,
interestAcumulated: 55512.9995123437,
maturityValue: 205512.9995123437,
noOfYears: 5,
rateOfInterest: 6.5
}
Maturity value: 205513.00
Interest gained: 55513.00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment