Function parameters destructuring

You can apply a destructuring assignment to function parameters as well. Let's see the following example:

1. function workout({gym}, times) {
2. console.log('Workout in ' + gym + ' for ' + times + ' times');
3. }
4. let thisWeek = {gym: 'Gym A'};
5. workout(thisWeek, 2); // Workout in Gym A for 2 times

As you can see, in line 1, we use object destructuring syntax to extract the gym variable from the first argument of the workout() function. In this way, the argument passed to the workout() function cannot be null or undefined. Otherwise, TypeError will be thrown. You can pass a number, a string, an array, or a function to the workout() function and JavaScript won't complain about it, although you will get undefined as a value for the gym variable.

Let's look at another example, in which we will perform a further destructuring of a destructured variable:

1. function workout({gym, todos}) {
2. let [first] = todos;
3. console.log('Start ' + first + ' in ' + gym);
4. }
5. let today = {gym: 'Gym A', todos: ['Treadmill']};
6. workout(today); // Start Treadmill in Gym A
7. workout({gym: 'Gym B'}) // throw TypeError

In line 1, we do a parameter destructuring of the first argument, and in line 2 we do a further destructuring of the todos variable. In this way, the argument passed to the workout() function must have a todos property and its value is an array. Otherwise, TypeError will be thrown, as you can see in line 7. This is because, in line 2, JavaScript cannot do destructuring on undefined or null. We can improve this by giving todos a default value, as follows:

1. function workout({gym, todos=['Treadmill']}) {
2. let [first] = todos;
3. console.log('Start ' + first + ' in ' + gym);
4. }
5. workout({gym: 'Gym A'}); // Start Treadmill in Gym A
6. workout(); // throw TypeError

As you can see, in line 1, we only give todos a default value and we have to call the workout() function with a parameter. Calling it without any parameters, as in line 6, will still throw an error. It is because JavaScript still cannot do destructuring on undefined to get a value for the gym variable. And if you try to assign a default value to gym itself, such as workout({gym='', ...), it won't work. You need to assign the entire parameter destructuring a default value, like this:

function workout({gym='', todos=['Treadmill']} = {}) {
...
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.71.21