Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Object Destructuring Default Parameters

I'm trying to figure out if there's a way to use object destructuring of default parameters without worrying about the object being partially defined. Consider the following:

(function test({a, b} = {a: "foo", b: "bar"}) {    console.log(a + " " + b);  })();

When I call this with {a: "qux"}, for instance, I see qux undefined in the console when what I really want is qux bar. Is there a way to achieve this without manually checking all the object's properties?

like image 517
user3019273 Avatar asked Oct 26 '14 21:10

user3019273


People also ask

How do you give a default value in an object Destructuring?

Default values can be specified using = , and will be used as variable values if a specified property does not exist in the passed object.

What is object Destructuring in ES6?

Object destructuring is new syntax introduced in ES6. It helps create variables by extracting the object's properties in a much simpler way.

How do you Destructure an array of objects?

To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element.

What is object Destructuring in JS?

Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. Destructuring allows us to extract multiple properties, or items, from an array​ at a time.


1 Answers

Yes. You can use "defaults" in destructuring as well:

(function test({a = "foo", b = "bar"} = {}) {    console.log(a + " " + b);  })();

This is not restricted to function parameters, but works in every destructuring expression.

like image 132
Bergi Avatar answered Oct 23 '22 23:10

Bergi