In JavaScript, a function can return only a single value. Still, if you want to return multiple values, you have to return an array or object.
Suppose you have a getSalesRecord()
function that fetches the first quarter sales record from the database. Then, with the help of an array, you can return those three sales records by returning them as array elements.
function getSalesRecord(){ return [10000, 9243, 13287]; }
Array destructuring enables you to unpack array elements to distinct variables. So, using an array, you can return multiple values from a function very easily.
let [January, February, March] = getSalesRecord();
Suppose a productDetails()
function get details about Amazon Echo from the database as an object. Then, you don't have to worry because you can return an object from a function.
function productDetails(){ return { pdtName:'Amazon Echo Dot', pdtPrice:39.99, pdtQuantity:25 }; }
If you want to extract the properties of an object, then you can use object destructuring.
let {pdtName, pdtQuantity, pdtPrice} = productDetails();