How to return multiple values from a function in JavaScript

4 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

Related questions

...