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.

1

3 Answers 3

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));

Sign up to request clarification or add additional context in comments.

Comments

0

No. Not possible with regular JavaScript.

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

Comments

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"});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.