Is it possible to overload functions/methods in JS like in C#?
Trying to overload functions in JS if possible to take different number of arguments.
Is it possible to overload functions/methods in JS like in C#?
Trying to overload functions in JS if possible to take different number of arguments.
In JavaScript, you cannot natively overload functions or methods in the same way as you can in C#. But you can achieve similar functionality by checking the number or types of arguments passed to a single function:
const example = (...args) => {
const [firstArgument, secondArgument] = args;
if (args.length === 0) {
return 'No arguments case';
} else if (args.length === 1) {
return `One argument case: ${firstArgument}`;
} else if (args.length === 2) {
return `Two arguments case: ${firstArgument} ${secondArgument}`;
}
}
console.log(example());
console.log(example(1));
console.log(example(1, 2));
No. Not possible with regular JavaScript.
You can with typescript -- see https://www.typescriptlang.org/docs/handbook/2/functions.html
Unfortunately JavaScript does not have support for direct overloaded functions. Something close you can do is structure/array unpacking:
const overloaded = (({par1, par2}) => {
if (par1 !== undefined) {
par1 += " overload 1";
console.log(par1);
}
if (par2 !== undefined) {
par2 += " overload 2";
console.log(par2);
}
});
overloaded({par1: "test"});
overloaded({par2: "test"});