Outline

Named parameters is a feature with JavaScript functions that makes it easier to deal with long lists of parameters. Look at this example to start:

function printDogInfo(name, breed, age, foodPreference, likesToWalk) {
  return `${name} is a ${breed}, likes to eat ${foodPreference}, and is ${age} years old. ${name}${likesToWalk ? ' also likes to walk.' : ' does not like to walk.'}`;
}

This function has 5 parameters. Each of them needs to be passed in for the result to make sense, and they all have to be passed in in the correct order too. If you mix up name and breed, for example, the result won't be correct. We can make this function easier to call by using named parameters. All we need to do for that is to wrap the parameter list in curly brackets:

function printDogInfo({ name, breed, age, foodPreference, likesToWalk }) {
  return `${name} is a ${breed}, likes to eat ${foodPreference}, and is ${age} years old. ${name}${likesToWalk ? ' also likes to walk.' : ' does not like to walk.'}`;
}

Now it looks like all we pass into this function is an object, and that's really what it is. We can call the function like this:

const dogInfo1 = printDogInfo({ age: 4, breed: 'Labradoodle', foodPreference: 'dry food', likesToWalk: true, name: 'Duke'});

As the parameters for this function, we pass in an object with key/value pairs. Many IDEs will show tooltips telling you what needs to be passed in as well. With named parameters, the developer doesn't have to remember what parameters are needed for the function, because the IDE will tell them, and they don't have to be in a particular order. It's a much better developer experience, especially when dealing with long lists of parameters.

You can learn more about named parameters in this blog post.

 

I finished! On to the next chapter