{

Javascript function return multiple values


Javascript functions return a single value only as given.

The value is a primitive type or a javascript valid object.

function myfunction(){
    return values;
}

javascript does not return multiple values from a function And below is an invalid code in javascript

function myfunction(){
    return (values1,values2);
}

How do you return multiple values from a function in javascript?

You can use multiple values included in the following types to return from the function

  • Array
  • Set
  • Object

Function return multiple values in two ways

  • Add the values to Array or set or object type variable and return a single variable
  • Return multiple values using ES6 Array or object destructing operator.

Javascript function return multiple values

ES6 Destructuring assignment syntax allow you to extract values from an array of objects.

Here is an syntax.

let [variables]= array/object/nestedobject

Here is an array Destructuring assyignment return multiple values from an function.

function myfunc1() {
  const p = 8;
  const q = 4;
  const r = 7;

  return [p, q,r];
}
const [p, q, r] =myfunc1();

Here is an object destructuring example

function myfunc1() {
  const p = 1;
  const q = 2;
  const r = 2;

  return { 
     first: p, 
     second: q ,
     third:r
   }; 
}
const [p, q, r] =myfunc1();
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.