User Tools

Site Tools


Java Script Named Parameters In Functions

To use named parameters, we can pass an object to a function and then access the properties of that object within the function.
This approach makes the code more readable and allows you to easily pass multiple parameters to a function, including optional parameters with default values:

function bookHotel({ city, nights, isBreakfastIncluded = false }) {
  if (!city || !nights) {
    console.log('Please specify the city and the number of nights.');
  console.log(`Booking a hotel in ${city} for ${nights} nights.`);
  if (isBreakfastIncluded) {
    console.log('Breakfast is included.');
bookHotel({ city: 'Paris', nights: 3, isBreakfastIncluded: true });
// Booking a hotel in Paris for 3 nights.
// Breakfast is included.
bookHotel({ city: 'London', nights: 2 });
// Booking a hotel in London for 2 nights.
bookHotel({ city: 'New York' });
// Please specify the city and the number of nights.

By using destructuring syntax within the function signature, you can specify the expected named parameters, and also provide default values for them.

This pattern is becoming increasingly common in modern JavaScript code, especially when you have a function that might accept numerous parameters, some of which are optional. It can make the code more self-documenting and help avoid errors that might arise from passing parameters in the wrong order.
java-script/named-parameters-in-functions.txt · Last modified: 2023/08/10 15:30 by odefta