# Named Parameters using Destructured Objects

Yay, Destructured Objects to the rescue πŸŽ‰

Since JavaScript doesn’t natively support named parameters. This is a cool way around this issue. No more worrying about the specific order of inserting your arguments πŸ‘

// Boo, arguments must be in specific order
function meal(protein, carb, veggie) {}
meal('πŸ₯©', '🍚', 'πŸ₯¦');

// Yay, arguments can be in any order
function meal2({ protein, carb, veggie }) {}
meal2({ carb: '🍚', veggie: 'πŸ₯¦', protein: 'πŸ₯©' });

Here's how you can access the value within the function

function meal2({ protein, carb, veggie }) {
  console.log(protein, veggie, carb); // πŸ₯©  πŸ₯¦  🍚
}
meal2({ carb: '🍚', veggie: 'πŸ₯¦', protein: 'πŸ₯©' });

# Add a Default to Safe Guard from Error

If you forget to pass an argument to the function, you will get a TypeError

function meal2({ protein, carb, veggie }) {}

meal2(); // No Argument

// This will throw a "TypeError: Cannot destructure property ..."

Solution: To solve this, you can set a default empty object, {}. So if you forget to pass an argument, you will get undefined instead.

function meal2({ protein, carb, veggie } = {}) { // πŸ‘ˆ

}

meal2(); // No Argument

// This will return "undefined"

# Combining with Default Parameters

You can also set default parameter within the object.

function meal2({ protein = 'protein', carb, veggie } = {}) {
  console.log(
    protein, // 'protein'
    veggie, // undefined
    carb, // '🍚'
  );
}

meal2({ carb: '🍚' });

# Community Examples

# Combining with Optional Arguments

RanqueBenoit: Great if some are optional arguments too! Also for default values.

function oneFunc(options = {}) {
  let defaults = { one: 1 };
  options = { ...defaults, ...options };

  return options.one;
}

oneFunc(); // 1
oneFunc({}); // 1
oneFunc({ one: 2 }); // 2

Thanks: @RanqueBenoit

# Resources


Related Tidbits