🧠 Function Overloading in JavaScript
1️⃣ What Happens When We Define Functions with the Same Name
function greet() {
console.log("Hello, World!");
}
function greet(name) {
console.log("Hello, " + name);
}
greet(); // Output: Hello, undefined
greet("Ayush"); // Output: Hello, Ayush
✅ JavaScript overwrites the first greet() with the second one.
Only the last defined function is used.
2️⃣ Simulating Function Overloading Using arguments
function add() {
if (arguments.length === 2) {
return arguments[0] + arguments[1];
} else if (arguments.length === 3) {
return arguments[0] + arguments[1] + arguments[2];
} else {
return "Invalid number of arguments.";
}
}
3️⃣ Using Spread Operator (...args)
function addSpread(...args) {
if (args.length === 2) {
return args[0] + args[1];
} else if (args.length === 3) {
return args[0] + args[1] + args[2];
} else {
return "Invalid number of arguments.";
}
}