0

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.

ASh
  • 34,632
  • 9
  • 60
  • 82
jycld
  • 1
  • [https://stackoverflow.com/questions/456177/function-overloading-in-javascript-best-practices](https://stackoverflow.com/questions/456177/function-overloading-in-javascript-best-practices) – quaabaam Mar 20 '23 at 21:46

3 Answers3

1

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));
piskunovim
  • 392
  • 2
  • 6
0

No. Not possible with regular JavaScript.

You can with typescript -- see https://www.typescriptlang.org/docs/handbook/2/functions.html

Stand__Sure
  • 253
  • 1
  • 13
0

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"});
0x59
  • 99
  • 1
  • 10