Javascript ES6 — Destructuring Functions # 7

So far you learn how to destructure arrays and objects, so if you don’t already follow the previous courses, I suggest taking a look to them before jumping into destructuring functions.

Destructure a returned object

Okay let’s now go for some real examples, We start with a function that returns an object, for that you create a getStudentInfo function, that has no argument, we’ll use the es6 arrow function syntax, add the fat arrow, this function will return an object, so open the parenthesis, and add the brackets, and add the properties name, and age.

const getStudentInfo = () => ({
 name: "John Doe",
 age: 22,
});

I use for this example the arrow functions object literal syntax, however if you
want to simplify the syntax, comment out the
getStudentInfo function,

// const getStudentInfo = () => ({
//   name: "John",
//   age: 22,
// });

copy the object that has the properties name and age,
remove all of that, add the brackets, create a new variable
studentInfo, paste the object into it, and return the
studentInfo object.

const getStudentInfo = () => {
 const studentInfo = {
   name: "John Doe",
   age: 22,
 };

 return studentInfo;
};

I prefer the first presentation, so I’ll remove this function, and uncomment the
arrow function presentation. Let’s now assign the return object to a variable
studentInfo;

const student = getStudentInfo();

Console log the student value

console.log(student);

What if you want to get some specific values from the returned object and store
them into variables, instead of storing the whole object that contains the
name and age, for that, you’ve to destructure the
returned object, so replace the student variable, with the
brackets.

const { } = getStudentInfo();

And set the name of the properties you want to get, let’s go for booth
name and age, now you map the values of the properties
name and age from the object
getStudentInfo into two variables name and
age

const { name, age } = getStudentInfo();

Console log the values of name and age

console.log(name, age);

The order doesn’t really matter, you can swap the order of age and
name, it still works fine, because it’s just an object.

const { age, name } = getStudentInfo();

Destructure Functions Arguments

So far, you learn how to destructure a returned object from a function, let’s
now move to another example, where you’ll use the destructuring syntax on the
function arguments part, I need you to focus more, you’ll confront some
complexity. Let’s start with a function getFullName that has as an
input two arguments firstName and lastName, and let’s
give each of these arguments a default value, respectively John and
Doe, Okay, a fat arrow because we’re trendy, and we
use arrow functions, this function will return the values of the
firstName and the lastName as an output. Very Simple.

const getFullName = (firstName = "John", lastName = "Doe") => {
 return `${firstName} ${lastName}`;
};

Now, go for a person variable and assign to it the returned value
of the function getFullName

const person = getFullName();

Console log the person value

console.log(person);

Voila, you’ve got a John Doe as a result, even without defining the
firstName and the lastName arguments, because they’ve
already some predefined values. You can replace these default values, so
firstName will be Maria and the lastName
Brewer, you’re simply forcing the default values to some new
values.

let person = getFullName("Maria", "Brewer");

This kind of syntax of the
getFullName(Maria, Brewer) has two cons.
The first one is, this kind of presentation it is not explicit, in other words,
you don’t know the name of each argument, you don’t know exactly if the value of
Maria is a firstName or whatever, you’ve to go into
the function to find out this info. The second problem is when you change the
order of the arguments.

let person = getFullName("Brewer", "Maria");

The firstName now becomes Bewer and the
lastName becomes Maria. To resolve these problems,
you’ve to change this presentation,and instead of parsing strings as arguments,
now you’ve to parse an object, with two properties
firstName and lastName.

let person = getFullName({
 firstName: "Maria",
 lastName: "Brewer",
});

Now you can define each argument, with its specific value, but wait a minute,
You can’t parse an object as an argument for the function when you call the
getFullName function unless you’re using the same object format as
an argument when you define the function getFullName. So, now use
an object as an argument when you create the function, and the properties
firstName and lastName will stay the same.

let getFullName = ({ firstName = "John", lastName = "Doe" }) => {
 return `${firstName} ${lastName}`;
};

So, When you create a function, and you use the brackets as an argument of the
function, in this case, you’re using the destructuring syntax, and to give you
an idea about the real presentation on what you’re achieving with this syntax,
is like the following. The left-hand side is the destructuring source which is
used on the function argument (point into the function argument),

let { firstName = "John", lastName = "Doe" } =

and the right-hand side is the destructuring target which is used when you fill
up the argument after calling the functions (point into the function call
argument)

let { firstName = "John", lastName = "Doe" } = {
 firstName: "Maria",
 lastName: "Brewer",
};

Comment out this Object, you will need it later.

// let { firstName = "John", lastName = "Doe" } = {
//   firstName: "Maria",
//   lastName: "Brewer",
// };

Now even if you change the order of the properties, firstName will
still Maria, and lastName will still
Brewer, the order doesn’t matter at all.

let person = getFullName({
 lastName: "Brewer",
 firstName: "Maria",
});

What if you remove the argument value when you call your function,

let person = getFullName();

Ahaaa, you’re getting an error now, telling you that you
Cannot destructure property ‘firstName’ of ‘undefined’ or ‘null’,
pause the video, and think little why you’re having this error. Let’s explain
Why you’re getting this error, but first, uncomment this part

let { firstName = "John", lastName = "Doe" } = {
 firstName: "Maria",
 lastName: "Brewer",
};

When you remove the object from the function call, you leave the left the
right-hand side of the destructuring presentation empty, and you’ll be more in
this kind of presentation

let { firstName = "John", lastName = "Doe" }

So, you can define the right-hand side of the destructuring presentation from
the function argument, by assigning an empty object.

let getFullName = ({ firstName = "John", lastName = "Doe" } = {}) => {
 return `${firstName} ${lastName}`;
};

Or do the same change from the function call by doing that

let person = getFullName({});

These two changes will be the equivalent of that, which will complete the
destructuring assignment presentation.

let { firstName = "John", lastName = "Doe" } = {}

Conclusion

That’s it, I do my best by going into the details little bit, but once the
concept clicks into your mind, this will be super easy to implement into your
code.

Leave a Reply

Your email address will not be published. Required fields are marked *