How to bound variable which I pass through function to a specific parameter

Viewed 38

Very stupid question. For example I have a variable data and I have function DoSomething with two parameters par1 and par2. they are both optional parameters that would be null if I pass nothing. But I have only one variable data which I want to bound to the second parameter without touching first parameter. In different language I should write something like DoSomething(par2 = data) or DoSomething(par2: data) but all these examples will raise exception Uncaught SyntaxError: missing ). So what I did wrong?

4 Answers

If you have two optional parameters in JavaScript, just pass undefined to the first argument.

DoSomething(undefined, data);

undefined is the default value of arguments when they aren't passed in (DoSomething() would have both arguments be undefined) except when you set default values for optional arguments.

Another alternative is to pass in the arguments as an object, which requires changing the definition of the function and all calls to it: (?? is the Nullish coalescing operator

function DoSomething(args) {
  const par1 = args.par1 ?? "default value";
  const par2 = args.par2 ?? "default value";
}

// ....
DoSomething({ par2: "custom value" });
DoSomething({ par1: "custom value", par2: "customValue" });

Using TypeScript or JSDocs allows you to give guidance on how to send arguments in the IDE

You always can pass undefined or null as first parameter. SO it will be something like this:

DoSomething(undefined, data);

If you have multiple optional parameters, if you don't want to pass undefined.. you should use an object as the parameter.

// instead of DoSomething(param1, param2)
function DoSomething(param = {}) {
  const { param1, param2 } = param;

  //..do something with param1 and param2
}

DoSomething({ param2: 'somevalue' })

If you consider using typescript, it's even better because you can add the type to the param.

First of all, if you don't pass a parameter, it would be undefined, not null.

If you want to skip the first parameter, you still have to pass it in, just pass it in as something falsy (assuming your doSomething function handles that case).

const data = 'foo';

function doSomething(param1, param2) {
    if (param1) console.log(param1);
    if (param2) console.log(param2);
}

doSomething(null, data);

If you a similar functionality to Python, you can take in a single parameter, which is an object.

const data = 'foo';

function doSomething({ param1, param2 }) {
    if (param1) console.log(param1);
    if (param2) console.log(param2);
}

doSomething({ param2: data });

Related