How to Pass Object as Parameter in JavaScript ?
We’ll see how to Pass an object as a Parameter in JavaScript. We can pass objects as parameters to functions just like we do with any other data type. passing objects as parameters to functions allows us to manipulate their properties within the function.
These are the following approaches:
Table of Content
- Passing the Entire Object In a function
- Destructuring the Object
- Using ‘this’ keyword
Approach 1: Passing the Entire Object In a function
In this approach, we simply pass the entire object as a parameter to a function. This allows the function to access all properties of the object without explicitly passing each property individually.
Syntax:
// Define a function that takes an object as a parameter.......
function Function_Name(objectParameter) {
// write a logic ......
}
Example: This example shows the passing of an object as a parameter to the function.
Javascript
// Define an object let person = { name: "John" , age: 30 }; // Function that takes an object as a parameter function greet(personObj) { console.log( "Hello, " + personObj.name + "! You are " + personObj.age + " years old." ); } // Call the function and pass // the object as a parameter greet(person); |
Hello, John! You are 30 years old.
Approach 2: Destructuring the Object
When passing an object as a parameter to a function, destructuring enables us to extract specific properties directly within the function’s parameter list. This approach is particularly beneficial for enhancing code readability. Using this we can do a clean code.
Example: This example shows the destructuring the object properties by parameter.
Javascript
// Define an object let person = { name: "Beginner" , age: 25 }; // Function that takes destructured // object parameters function greet({ name, age }) { console.log( "Hello, " + name + "! You are " + age + " years old." ); } // Call the function and pass // the object as a parameter greet(person); |
Hello, Beginner! You are 25 years old.
Approach 3: Using ‘this’ keyword
In JavaScript, the ‘this’ keyword refers to the current object . This approach is particularly useful when we define a methods within object constructors or object literals.
Example: This example shows the use of “this” keyword for accessing the object properties.
Javascript
// Define an object constructor function Person(name, age) { this .name = name; this .age = age; // Method that uses 'this' to // access object properties this .greet = function () { console.log( "Hello, " + this .name + "! You are " + this .age + " years old." ); }; } // Create an instance of the Person object let person = new Person( "Beginner" , 25); // Call the method using 'this' person.greet(); |
Hello, Beginner! You are 25 years old.