skip to Main Content

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.

3

Answers


  1. No. Not possible with regular JavaScript.

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

    Login or Signup to reply.
  2. 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));
    Login or Signup to reply.
  3. 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"});
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search