====== Dynamic Function Invocation ======
The ;;;object[method](...);;; syntax is a common pattern in JavaScript that allows you to dynamically call a method on an object using a variable for the method name.
This pattern can be useful in various scenarios where you need to **call different methods based on conditions or user input, or when you want to create higher-order functions that can operate on different methods.**
===== General explanation =====
**object**: This represents any object that has methods. \\
**method**: This is a string containing the name of the method you want to call on the object. It can be a variable or a literal string. \\
**object[method]**: This accesses the method on the object with the name specified by the method string. \\
**object[method](...)**: This calls the accessed method, and you can pass any arguments that the method expects.
===== Examples =====
const obj = {
greet: function(name) {
console.log(`Hello, ${name}!`);
}
};
const methodName = 'greet';
obj[methodName]('John'); // Output: Hello, John!
function myConsole(method, ...items) {
console[method](items.join(', '));
}
myConsole('info', 1, 2, 3, 4);
const mathOperations = {
add: (x, y) => x + y,
subtract: (x, y) => x - y,
multiply: (x, y) => x * y,
divide: (x, y) => x / y
};
function calculate(operationName, a, b) {
const operation = mathOperations[operationName];
if (typeof operation === 'function') {
return operation(a, b);
} else {
throw new Error(`Unknown operation: ${operationName}`);
}
}
console.log(calculate('add', 5, 3)); // Output: 8
console.log(calculate('subtract', 10, 4)); // Output: 6
console.log(calculate('multiply', 2, 3)); // Output: 6
console.log(calculate('divide', 9, 3)); // Output: 3
Here, **calculate** is a function that takes the name of a mathematical operation and two operands. It looks up the corresponding function in the **mathOperations** object and invokes it. If the operation name is not found, it throws an error. This approach allows you to add new operations easily without modifying the **calculate** function.