Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Object destructuring and default parameters combined

Today I came across the following syntax which I didn't recognize:

const createUser = ({
  age = 1,
  name = 'Anonymous',
}) => ({
  age,
  name,
});


const defaultP = createUser({
  age: 5
});
console.log(defaultP);

I think it uses Object destructuring and default parameters in order to set defaults of the object which is send as an argument.

The syntax threw me a bit off because normally I see object destructuring only in the following manner:

let obj = {
   prop1: 1
}

const {prop1} = obj;

console.log(prop1);

Question:

How does this syntax work exactly?

like image 892
Willem van der Veen Avatar asked Sep 02 '25 04:09

Willem van der Veen


1 Answers

That syntax indeed uses Object Destructuring in order to extract default values from the parameter object. There are some examples in the Mozilla documentation that helps us understand the trick, check this out:

var {a = 10, b = 5} = {a: 3};
console.log(a); // 3
console.log(b); // 5

A possible disadvantage of your example is that the createUser method ignores all other values of the parameter object and always returns an object that contains only age and name. If you want to make this more flexible, we could use Object.assign() like this:

const createUser = (o) => Object.assign({ age: 1, name: 'Anonymous' }, o);

In this case, the user created will be an object that merges the parameter object with the default values. Note now that the default values are in the method body. With this method we can create users that contain other properties, example:

const superman = createUser({ name: 'Superman', type: 'superhero' });
console.log(superman);
// output: {age: 1, name: "Superman", type: "Superhero"}
like image 53
HugoTeixeira Avatar answered Sep 05 '25 00:09

HugoTeixeira