1

In C# you can do something like that:

class Program 
{
    static void Main(string[] args)
    {
        Sum(2, 2, d: 10);
    }

    static int Sum(int a, int b, int c = 0, int d = 0)
    {
        return a + b + c + d;
    }
}

Is there a way to do something similar with Javascript?

const foo = (a, b, c = 0, d = 0) => a + b + c + d;

And then call this function:

foo(2, 2, d = 10);

Or the only way is call this function this way?

foo(2, 2, undefined, 10);
aopanasenko
  • 460
  • 3
  • 13

2 Answers2

1

Yes you can do default parameters in JavaScript however there is no support for named parameters. So the arguments must follow the same order as parameters.

The javascript alternative is object destructuring:

const foo = ({a, b, c = 0, d = 0}) => a + b + c + d;

Which you can then call "out of order" with:

foo({b: 1, a: 2, d: 6})
Ben
  • 3,160
  • 3
  • 17
  • 34
  • thanks! When I saw this answer and drew a parallel with default props in React, I realized that the answer is very simple! – aopanasenko Apr 18 '20 at 11:12
0

With ES6, you can do something like this:

const hello = (name = 'John Doe', b) => {
  console.log(`Hello Mr ${name}`);
};

hello('Jagathish'); // Hello Mr Jagathish
hello(); // Hello Mr John Doe