![]() |
VOOZH | about |
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.
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
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
}
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.
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;
}
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".
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
Example: This example implements the above steps combined in sequence.
John 30