🎓 A1Learner
🔍
0 of 50 lessons completed

JavaScript Destructuring in Function Parameters

Destructuring in function parameters unpacks an options object at the door of a function. The function receives one object and names the values it needs.

Unpack the options object

The parameter list names the values the function needs. The caller passes one object with those values.

function greet({ name, city }) {
  console.log(name);
  console.log(city);
}
greet({ name: "Ana", city: "Portland" });

Defaults inside the parameters

A parameter can carry its own default. A missing option takes the default, and a passed option wins.

function buildCard({ title, size = 12 }) {
  console.log(title);
  console.log(size);
}
buildCard({ title: "Hello" });

A default for the whole object

The parameter itself can carry a default object. A call with no argument unpacks the empty default instead of failing.

function showUser({ name = "Guest" } = {}) {
  console.log(name);
}
showUser();
showUser({ name: "Ana" });

Example

function printOrder({ id, total, paid = false }) {
  console.log(id);
  console.log(total);
  console.log(paid);
}
printOrder({ id: 101, total: 45 });

Key points

  • Parameter destructuring: unpacking an object in the parameter list of a function
  • The caller passes one object, and the function names the values it needs.
  • A parameter can carry a default, like size = 10.
  • The whole parameter can carry a default object, so a call with no argument still works.
  • Use this shape when a function takes several options.

In this example, the function unpacks the order object in its parameter list. The id and total come from the object. The paid flag is missing, so its default false fills in.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does function draw({ color = "red" }) do when called as draw({})?