1

I want to write an overload of a function in javascript. I tried optional parameter but it don't work. What I tried:

let myFunction = (foo, bar) => {
 foo = (foo || 'FOO');
 console.log(foo + " " + bar);
}

Here I expect: foo bar

myFunction("foo","bar");

Here I expect: FOO bar

myFunction("bar");

Anyone knows how to pass optional parameters to a function ?

Olivier D'Ancona
  • 779
  • 2
  • 14
  • 30
  • 3
    You've passed that string as the *first* argument. If you want to pass it as the second argument, and pass nothing to `foo`, then use `myFunction(undefined, "bar")`. In general, the optional parameters should always come last. – Bergi Apr 22 '20 at 19:48
  • you could have a look [here](https://stackoverflow.com/q/48327804/1447675), if that is, what you want. – Nina Scholz Apr 22 '20 at 19:52
  • Does null work as well? – Olivier D'Ancona Apr 22 '20 at 19:54
  • The way you've currently written your function, even `false` would work. Of course, if `foo` were the second parameter, you wouldn't have to pass anything. – Brian McCutchon May 29 '20 at 06:46
  • Does this answer your question? [Pass only the second argument in javascript](https://stackoverflow.com/questions/50569300/pass-only-the-second-argument-in-javascript) – Brian McCutchon May 29 '20 at 06:54

1 Answers1

0

It's important to call a function with every parameters. Even with undefined values.

To obtain FOO bar

 myFunction( undefined, "bar")

Working js fiddle here

p.s: it's working with null as well

Olivier D'Ancona
  • 779
  • 2
  • 14
  • 30
  • 1
    "It's important to call a function with every parameters" isn't always true. It's rare for people to pass 2 arguments to `Array.prototype.map()`, for example. – Brian McCutchon May 29 '20 at 06:49