Open In App

How to Store an Object sent by a Function in JavaScript ?

Last Updated : 23 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

When a function in JavaScript returns an object, there are several ways to store this returned object for later use. These objects can be stored in variables, array elements, or properties of other objects. Essentially, any data structure capable of holding values can store the returned object.

Storing in a variable

Assigns the returned object to a variable for direct access within the same scope, offering simplicity and convenience in handling single objects.

Example: The below code uses a JavaScript variable to store an object sent by a function in JavaScript.

Javascript




function returnObject() {
    const GFG = {
        name: "GeeksforGeeks",
        est: 2009
    }
    return GFG;
}
 
const obj = returnObject();
console.log(obj.name,
    "was established in year:",
    obj.est);


Output

GeeksforGeeks was established in year: 2009

Storing in an array

Insert the returned object into an array, enabling management of multiple objects in a single data structure, suitable for scenarios requiring collection-based operations.

Example: The below code uses an JavaScript array to store an object sent by a function in JavaScript.

Javascript




function returnObject() {
    const GFG = {
        name: "GeeksforGeeks",
        est: 2009
    }
    return GFG;
}
 
let objArray = [];
objArray.push(returnObject());
console.log(objArray[0].name,
    "was established in year:",
    objArray[0].est);


Output

GeeksforGeeks was established in year: 2009



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads