Skip to content
Go back

JS Named Parameters

Published:  at  04:38 PM
2 mins read

Let me start with an apology for the title, which is a bit inaccurate. There are no native named parameters in Javascript.

Having said that, using ES6 awesome destructuring we can enact named parameters.

Now before demonstrating exactly how, I want to give two use cases where it can come in handy.

Usage

Before a function is executed all arguments passed are assigned to parameters based on its’ signature. That means object destructuring will perfectly here.

Instead of:

const myFunc = (organizationId, name, force, verbose) => {
  ...
}

// not the most readable function call somewhere in your code
myFunc(17, 'Test', true, false)

You can do this:

const myFunc = ({ organizationId, name, force, verbose }) => {
  ...
}

// not the most readable function call somewhere in your code
myFunc({ organizationId: 17, name: 'Test', force: true, verbose: false })
Say my name gif

The important thing to remember is that destructuring is based on same property name. The order does not matter.

Pro Tips

// renamed name to orgName
const myFunc = ({ orgId, name: orgName , force, verbose }) => {
  console.log(orgName); // 'Test'
}

myFunc({ orgId: 17, name: 'Test', force: true, verbose: false)
const myOtherFunc = ({ x = 1, y = 2, z = 3 } = {}) => {
  console.log(x, y, z); 
}

// x isn't passed thus received its default value
myOtherFunc({ y: 5, z: 10}) // 1 5 10



Previous Post
npm link magic
Next Post
Commit Leaderboard