How to use named parameters in JavaScript

Sep 15, 2023#javascript

Named parameters are not a built-in feature of JavaScript like they are in some other programming languages. However, you can achieve a similar effect by passing an object as a parameter to a function and then accessing the properties of that object within the function.

This approach is particularly helpful when you have functions with many optional parameters, as they make the function call more explicit and self-documenting, and you don’t need to remember the order of arguments.

For example, you can write a function like this:

function greet({name, age, city} = {}) {
  console.log(`Hello, ${name}! You are ${age} years old and live in ${city}.`);
}

greet({name: "Alice", age: 25, city: "New York"});
// Hello, Alice! You are 25 years old and live in New York.

This way, you can pass the arguments in any order and omit the ones you don’t need. You can also assign default values to the parameters in case they are missing.

function greet({ firstName = 'John', lastName = 'Doe', age = 30 }) {
  console.log(`Hello, ${firstName} ${lastName}! You are ${age} years old.`);
}

const person1 = {
  firstName: 'Alice',
  age: 25,
};

const person2 = {
  lastName: 'Smith',
};

greet(person1); // Hello, Alice Doe! You are 25 years old.
greet(person2); // Hello, John Smith! You are 30 years old.
greet({});      // Hello, John Doe! You are 30 years old.

However, keep in mind that it’s not true named parameters as seen in some other languages; it’s just a convention using objects to achieve a similar result.

Benefits of using named parameters

Improved readability and clarity. When you call a function, the parameter names make it clear what each value represents, which can be especially helpful for functions with many parameters or complex logic.

Flexibility in parameter order. You can pass arguments in any order, which is especially useful when a function has a large number of optional parameters. This flexibility makes the code more robust and less error-prone because you don’t have to rely on the order of arguments.

Easier to maintain. When you need to add, remove, or change parameters, you don’t have to worry about breaking existing calls to the function, as long as you keep the parameter names consistent.

Backward compatibility. When you add new parameters to a function that uses named parameters, existing calls to the function remain valid, as long as you don’t remove or change the names of existing parameters.