Open In App

How a Function Returns an Object in JavaScript ?

JavaScript Functions are versatile constructs that can return various values, including objects. Returning objects from functions is a common practice, especially when you want to encapsulate data and behavior into a single entity. In this article, we will see how a function returns an object in JavaScript.

Why return objects from Function?

How a Function Returns an Object?

When a function returns an object in JavaScript, it follows a specific sequence of steps. Let’s break down the working of a function returning an object



Function Definition

The process starts with defining a JavaScript function. This function will be responsible for creating and returning an object. The function can have parameters that allow you to customize the properties and values of the object it will return. Here’s an example of a function declaration:

function createPerson(name, age) {
// Function logic goes here
}

Object Creation

Within the function, you create a new object. You can initialize this object in various ways, either by using object literal notation or by calling a constructor function. The object will typically have properties and values, which can be set based on input parameters or any other logic you need:



function createPerson(name, age) {
let person = {
name: name,
age: age,
};
}

In this example, we create an object “person” with “name” and “age” properties based on the “name” and “age” parameters passed to the function.

Return Statement

To return the newly created object from the function, you use the return statement. The return statement specifies the value (in this case, the object) that the function will provide as its result when called:

function createPerson(name, age) {
let person = {
name: name,
age: age,
};
return person;
}

Function Invocation

To obtain the object returned by the function, you call the function and assign the returned value to a variable:

let john = createPerson("John", 30);

In this line of code, we call the “createPerson” function with arguments “John” and “30”, and the returned object is assigned to the variable “john”.

Using the Object

Now, you can work with the john object just like any other JavaScript object. You can access its properties, modify them, or use the object in your code as needed:

console.log(john.name); // Output: "John"
console.log(john.age); // Output: 30

Complete Implementation

Example: This example implements the above steps combined in sequence.




function createPerson(name, age) {
    let person = {
        name: name,
        age: age,
    };
    return person;
}
let john = createPerson("John", 30);
console.log(john.name); // Output: "John"
console.log(john.age); // Output: 30

Output
John
30
Article Tags :