How to Pass Object as Parameter in JavaScript ?
Last Updated :
22 Feb, 2024
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:
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
let person = {
name: "John" ,
age: 30
};
function greet(personObj) {
console.log( "Hello, " + personObj.name +
"! You are " + personObj.age + " years old." );
}
greet(person);
|
Output
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
let person = {
name: "Geeks" ,
age: 25
};
function greet({ name, age }) {
console.log( "Hello, " + name +
"! You are " + age + " years old." );
}
greet(person);
|
Output
Hello, Geeks! 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
function Person(name, age) {
this .name = name;
this .age = age;
this .greet = function () {
console.log( "Hello, " + this .name +
"! You are " + this .age + " years old." );
};
}
let person = new Person( "Geeks" , 25);
person.greet();
|
Output
Hello, Geeks! You are 25 years old.
Share your thoughts in the comments
Please Login to comment...