Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Is there an elegant way of passing an object of parameters into a function?
Passing an object of parameters to a function provides flexibility and improves code readability. This technique allows you to avoid positional parameters and makes your functions more maintainable.
Using Object Destructuring (Recommended)
The most elegant approach uses ES6 destructuring to extract object properties directly in the function parameter:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Object Parameters Example</title>
</head>
<body>
<h1>Passing Object Parameters to Functions</h1>
<div id="result"></div>
<button onclick="calculateSum()">Calculate Sum</button>
<script>
// Function using object destructuring
function addNumbers({ a, b, c, d }) {
return a + b + c + d;
}
// Object with parameters
const numbers = {
a: 22,
b: 33,
c: 7,
d: 9
};
function calculateSum() {
const result = addNumbers(numbers);
document.getElementById('result').innerHTML =
`The sum of ${numbers.a} + ${numbers.b} + ${numbers.c} + ${numbers.d} = ${result}`;
}
</script>
</body>
</html>
With Default Values
You can provide default values for missing properties:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Default Parameters Example</title>
</head>
<body>
<h1>Object Parameters with Defaults</h1>
<div id="output"></div>
<script>
// Function with default values
function createUser({ name, age = 25, role = 'user' }) {
return `Name: ${name}, Age: ${age}, Role: ${role}`;
}
// Test with partial data
const userData1 = { name: 'Alice' };
const userData2 = { name: 'Bob', age: 30, role: 'admin' };
document.getElementById('output').innerHTML = `
<p>${createUser(userData1)}</p>
<p>${createUser(userData2)}</p>
`;
</script>
</body>
</html>
Name: Alice, Age: 25, Role: user Name: Bob, Age: 30, Role: admin
Comparison of Approaches
| Method | Readability | Flexibility | Default Values |
|---|---|---|---|
| Positional Parameters | Low | Low | Limited |
| Object Destructuring | High | High | Built-in |
| Object Access | Medium | High | Manual |
Key Benefits
- Order Independence: Properties can be passed in any order
- Self-Documenting: Parameter names are explicit
- Optional Parameters: Easy to handle missing values
- Extensible: New parameters can be added without breaking existing calls
Conclusion
Object destructuring provides the most elegant way to pass multiple parameters. It improves code readability and makes functions more flexible and maintainable.
Advertisements
