Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destructure option argument with all default values in ES6?

I use ES6 features with babel compiler. I have a function which takes option object as an argument:

function myFunction({ option1 = true, option2 = 'whatever' }) {
    console.log(option1, option2);
    // do something...
}

When I call it, destructuring happens and everything works well. I want to call it with default options most of the time, so I do:

myFunction({}); // true 'whatever'

but it looks little bit strange. It would much more cleaner just call:

myFunction(); // TypeError: Cannot read property 'option1' of undefined

Is it possible?

like image 401
madox2 Avatar asked Dec 14 '15 20:12

madox2


People also ask

How do I set default value in Destructuring?

Default value It is not used if the property has value null . The default value can be any expression. It will only be evaluated when necessary. const { b = console.log("hey") } = { b: 2 }; // Does not log anything, because `b` is defined and there's no need // to evaluate the default value.

How do you Destructure an object in es6?

When destructuring the objects, we use keys as the name of the variable. The variable name must match the property (or keys) name of the object. If it does not match, then it receives an undefined value. This is how JavaScript knows which property of the object we want to assign.

Can we Destructure function in JavaScript?

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.

Can we Destructure array in JavaScript?

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. const [var1, var2, ...]


1 Answers

Yes, you just have to provide a default value for the complete argument:

function myFunction({option1 = true, option2 = 'whatever'} = {}) {
//                                                         ^^^^
    console.log(option1, option2);
    // do something...
}
like image 66
Bergi Avatar answered Oct 20 '22 02:10

Bergi