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
How to call the key of an object but return it as a method, not a string in JavaScript?
In JavaScript, you can call object methods dynamically using bracket notation instead of dot notation. This allows you to access and execute object methods using string keys, which is useful when the method name is determined at runtime.
Basic Dynamic Method Access
You can use bracket notation obj[key]() to call methods dynamically:
const obj = {
greet: function() {
console.log("Hello!");
},
farewell: function() {
console.log("Goodbye!");
}
};
const methodName = "greet";
obj[methodName](); // Calls obj.greet()
Hello!
Using Object.keys() to Get Available Methods
You can combine Object.keys() with dynamic method calls to access methods by their position:
const calculator = {
add: function(a, b) {
return a + b;
},
multiply: function(a, b) {
return a * b;
}
};
const keys = Object.keys(calculator);
console.log("Available methods:", keys);
// Call first method dynamically
const firstMethod = keys[0];
console.log(`Calling ${firstMethod}:`, calculator[firstMethod](5, 3));
Available methods: [ 'add', 'multiply' ] Calling add: 8
Arrow Functions as Methods
The same approach works with arrow functions:
const actions = {
start: () => console.log("Starting process..."),
stop: () => console.log("Stopping process..."),
restart: () => console.log("Restarting process...")
};
const operation = "restart";
actions[operation](); // Calls actions.restart()
Restarting process...
Complete Example with Error Handling
Here's a robust example that checks if the method exists before calling it:
const mathOperations = {
square: (x) => {
console.log(`Square of ${x} is ${x * x}`);
return x * x;
},
cube: (x) => {
console.log(`Cube of ${x} is ${x * x * x}`);
return x * x * x;
}
};
function callMethod(obj, methodName, ...args) {
if (typeof obj[methodName] === 'function') {
return obj[methodName](...args);
} else {
console.log(`Method '${methodName}' not found`);
}
}
callMethod(mathOperations, "square", 4);
callMethod(mathOperations, "cube", 3);
callMethod(mathOperations, "invalid", 2);
Square of 4 is 16 Cube of 3 is 27 Method 'invalid' not found
Use Cases
This pattern is particularly useful for:
- Building dynamic APIs where method names come from user input
- Creating command pattern implementations
- Implementing plugin systems
- Route handling in web applications
Conclusion
Dynamic method calling using bracket notation allows you to execute object methods based on string keys. Always validate that the property exists and is a function before calling to avoid runtime errors.
