How to return multiple values from function in JavaScript

4 Answers

0 votes
function f() { 
    const a = 9;
    const b = 4;
    const c = 298;
 
    return [a, b, c];
} 
 
const arr =  f();
 
const x = arr[0];
const y = arr[1];
const z = arr[2];
 
console.log(x, y, z); 
 
 
 
 
/*
run:
 
9, 4, 298
 
*/
 

 



answered Apr 16, 2019 by avibootz
edited Dec 30, 2021 by avibootz
0 votes
const [x, y, z] = (function(){ return [5, 8, 2]; })();
          
console.log(x, y, z); 
 
 
 
/*
run:
 
5, 8, 2
 
*/

 



answered Apr 17, 2019 by avibootz
edited Dec 30, 2021 by avibootz
0 votes
const {x, y, z} = (function(){ return {x: 5, y: 2, z: 9} })();
         
console.log(x, y, z); 

 
 
 
/*
run:
 
5, 2, 9
 
*/

 



answered Apr 17, 2019 by avibootz
edited Dec 30, 2021 by avibootz
0 votes
const f = function() {
    const a = 22;
    const b = 65;
    const c = 89;
    return {
        vala: a,
        valb: b,
        valc: c
    };
};
 
const rv = f();
 
const x = rv.vala;
const y = rv.valb;
const z = rv.valc;
          
console.log(x, y, z); 
 

 
 
 
/*
run:
 
22, 65, 89
 
*/

 



answered Apr 17, 2019 by avibootz
edited Dec 30, 2021 by avibootz

Related questions

...