Is there a way to provide named parameters in a function call in JavaScript?

Viewed 294869

I find the named parameters feature in C# quite useful in some cases.

calculateBMI(70, height: 175);

What can I use if I want this in JavaScript?


What I don’t want is this:

myFunction({ param1: 70, param2: 175 });

function myFunction(params){
  // Check if params is an object
  // Check if the parameters I need are non-null
  // Blah blah
}

That approach I’ve already used. Is there another way?

I’m okay using any library to do this.

12 Answers

Calling function f with named parameters passed as the object

o = {height: 1, width: 5, ...}

is basically calling its composition f(...g(o)) where I am using the spread syntax and g is a "binding" map connecting the object values with their parameter positions.

The binding map is precisely the missing ingredient, that can be represented by the array of its keys:

// map 'height' to the first and 'width' to the second param
binding = ['height', 'width']

// take binding and arg object and return aray of args
withNamed = (bnd, o) => bnd.map(param => o[param])

// call f with named args via binding
f(...withNamed(binding, {hight: 1, width: 5}))

Note the three decoupled ingredients: the function, the object with named arguments and the binding. This decoupling allows for a lot of flexibility to use this construct, where the binding can be arbitrarily customized in function's definition and arbitrarily extended at the function call time.

For instance, you may want to abbreviate height and width as h and w inside your function's definition, to make it shorter and cleaner, while you still want to call it with full names for clarity:

// use short params
f = (h, w) => ...

// modify f to be called with named args
ff = o => f(...withNamed(['height', 'width'], o))

// now call with real more descriptive names
ff({height: 1, width: 5})

This flexibility is also more useful for functional programming, where functions can be arbitrarily transformed with their original param names getting lost.

This is admittedly pseudo-code, but I believe it'll work (I know it works in Typescript; I'm adopting it for JavaScript)

// Target Function
const myFunc = (a=1,b=2,c=3) => {a+b+c}

// Goal usage:
myFunc(a=5, b=6) // 14
myFunc(c=0) // 3

// set your defaults
const myFuncDefaults = {a:1, b:2, c:3};

// override them with passed params
const myFuncParams = (params) => { return Object.assign(myFuncDefaults, params)}


// use the overloaded dict as the input
const myFunc2 = (params) => {
  let {a, b, c} = myFuncParams(params);
  return myFunc(a, b, c)
}

// Usage:
myFunc({a:5, b:6}) // 14
myFunc({c:0}) // 3

// Written more succinctly:
const myFunc = (params) => {
  let {a,b,c} = Object.assign({a:1, b:2, c:3}, params)
  return a + b + c
}

FWIW Typescript makes this kind of nice with hinting:

interface IParams {
  a: number;
  b: number;
  c: number;
}

const myFunc = (params: Partial<IParams>): number => {
  const default: IParams = {a:1, b:2, c:3};
  let {a, b, c} = Object.assign(default, params)
  return a + b + c
}

Yes, well, kind of. I've found 2 solutions. I'll explain just one.

In this solution, we give up positional args, tho.

We can use an object (almost identical to a dict in python) to pass the arguments.

In this example, I'm using the function to generate the name of a image file

//first we define our function with just ONE argument
function name_of_img(img_desc){

  // with this step, any undefined value will be assigned a value
  if(img_desc.size == undefined) {img_desc.size = "400x500"}
  if(img_desc.format == undefined) {img_desc.format = ".png"}

  console.log(img_desc.size + img_desc.format)
}

//notice inside our function we're passing a dict/object
    
name_of_img({size: "200x250", format=".jpg"})
// returns "200x250.jpg"

name_of_img({size: "1200x950"})
// returns "1200x950.png"

We can modify this example, so we can use positional arguments too, we can also modify it so non valid arguments can be passed, I think I will make a github repository about this

Contrary to what is commonly believed, named parameters can be implemented in standard, old-school JavaScript (for boolean parameters only) by means of a simple, neat coding convention, as shown below.

function f(p1=true, p2=false) {
    ...
}

f(!!"p1"==false, !!"p2"==true); // call f(p1=false, p2=true)

Caveats:

  • Ordering of arguments must be preserved - but the pattern is still useful, since it makes it obvious which actual argument is meant for which formal parameter without having to grep for the function signature or use an IDE.

  • This only works for booleans. However, I'm sure a similar pattern could be developed for other types using JavaScript's unique type coercion semantics.

Related