1

So imagine we got a function like below, and I want to use the default value for the first parameter a and a custom value for second parameter b.

const func = (a = 1 , b = 2) => {
    console.log("a is equal to " + a, " and b is equal to " + b)
}

I want to just pass one value for parameter b. something like this:

func(b : 7);
// I want it to print: a is equal to 1 and b is equal to 7

How can I achieve it in JavaScript?

mgh
  • 377
  • 2
  • 4
  • 14
  • If you don't want to change the function signature, you would need to call it like so `func(undefined, 7)` – Jake Jul 15 '19 at 13:17

2 Answers2

0

You modify your function to receive an object and then inside that object you can also define default values for some properties like a and b.

const func = ({ a = 1, b = 2 }) => {
  console.log("a is equal to " + a, " and b is equal to " + b)
}

func({b: 3})
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • So how about methods like `server.listen(port, hostname, backlog, callback)`? all its parameters are optional. – mgh Jul 15 '19 at 13:15
  • Unless the function can receive an object where you can specify name of the parameter you want to pass there is no way to use named parameters. – Nenad Vracar Jul 15 '19 at 13:17
0

try to use RORO pattern, to pass object into function

Pasha K
  • 357
  • 1
  • 7