How to return multiple values from a function in JavaScript

7 Answers

0 votes
// Returning an Array

function getCoordinates() {
    return [31.4820, -52.1673]; // Latitude and Longitude
}

const [latitude, longitude] = getCoordinates();

console.log(latitude);  
console.log(longitude);



/*
run:

31.482
-52.1673

*/

 



answered Apr 7, 2025 by avibootz
0 votes
// Returning an Object

function getUserInfo() {
    return {
        name: "Emma",
        age: 42,
        email: "emma@email.com"
    };
}

const user = getUserInfo();

console.log(user.name);  
console.log(user.age);   
console.log(user.email);   



/*
run:

Emma
42
emma@email.com

*/

 



answered Apr 7, 2025 by avibootz
0 votes
// Returning an Object

function getUserInfo() {
    return {name: "Emma", age: 42, email: "emma@email.com"};
}

const { name, age, email } = getUserInfo();

console.log(name); 
console.log(age);       
console.log(email);       



/*
run:

Emma
42
emma@email.com

*/

 



answered Apr 7, 2025 by avibootz
0 votes
// Combine an object and array and return the structure

function getInfo() {
    return {
        user: {name: "Emma", age: 42, email: "emma@email.com"},
        stats: [5, 8, 9, 3]
    };
}

const { user, stats } = getInfo();

console.log(user); 
console.log(user.name); 
console.log(user.age);       
console.log(user.email);       

console.log(stats); 
console.log(stats[0]); 
console.log(stats[1]); 



/*
run:

{ name: 'Emma', age: 42, email: 'emma@email.com' }
Emma
42
emma@email.com
[ 5, 8, 9, 3 ]
5
8

*/

 



answered Apr 7, 2025 by avibootz
0 votes
// Destructuring assignment:
// The function is immediately invoked (IIFE).
// It returns an array [5, 8, 2].
// The destructuring syntax extracts each element into x, y, and z.
const [x, y, z] = (function() {
    return [5, 8, 2];
})();


console.log(x, y, z);


/*
run:

5, 8, 2

*/

 



answered May 1 by avibootz
0 votes
// Object destructuring:
// The function below is an IIFE (Immediately Invoked Function Expression).
// It returns an object with properties x, y, and z.
const { x, y, z } = (function() {
    return { x: 5, y: 2, z: 9 };
})();


console.log(x, y, z);



/*
run:

5, 2, 9

*/

 



answered May 1 by avibootz
0 votes
// Define a function expression and store it in 'f'.
// The function creates three local constants (a, b, c)
// and returns them inside an object with property names
// vala, valb, and valc.
const f = function() {
    const a = 22;
    const b = 65;
    const c = 89;

    // Return an object whose properties reference the local variables
    return {
        vala: a,
        valb: b,
        valc: c
    };
};

// Call the function and store the returned object in 'rv'
const rv = f();

// Extract each property manually from the returned object
const x = rv.vala;
const y = rv.valb;
const z = rv.valc;

console.log(x, y, z);



/*
run:

22, 65, 89

*/

 



answered May 1 by avibootz
...