30 Days Of JavaScript

Day 5: Functions Part 1

Lesson 6: Multiple Returns

You can only return one value from a JavaScript function. However that value can be any data type you want. So, let's take our unit converter and see how we could return more than one conversion.

1function convertMeasurement(measurement, unit) {
2  if (unit === "cm") {
3    const inches = measurement / 2.54;
4    const feet = measurement / 30.48;
5    const yards = measurement / 91.44;
6
7    const imperialMeasures = {
8      inches: inches,
9      feet: feet,
10      yards: yards,
11    };
12
13    return imperialMeasures;
14  }
15
16  if (unit === "inches") {
17    const mm = measurement * 30.48;
18    const cm = measurement * 2.54;
19    const meters = measurement * 91.44;
20
21    const metricMeasures = {
22      mm: mm,
23      cm: cm,
24      meters: meters,
25    };
26
27    return metricMeasures;
28  }
29}

Here we are doing the calculations we need and then returning a single object, that contains multiple values.

In this playground I want you to take the function above and replace the function below that doesn't work.

We can make some improvements though

In the returned object above you will see we have properties with the same names as the variables created just above them:

1const mm = measurement * 30.48;
2const cm = measurement * 2.54;
3const meters = measurement * 91.44;
4
5const metricMeasures = {
6  mm: mm,
7  cm: cm,
8  meters: meters,
9};

If you think the whole mm: mm, business is needless repetition, you would be right! JavaScript has some nice syntactic sugar where we can omit the second half of this, if the names are the same. So it can be simplified to:

1const mm = measurement * 30.48;
2const cm = measurement * 2.54;
3const meters = measurement * 91.44;
4
5const metricMeasures = {
6  mm,
7  cm,
8  meters,
9};

or, if we want to get really short we can do this:

1const metricMeasures = {
2  mm: measurement * 30.48,
3  cm: measurement * 2.54,
4  meters: measurement * 91.44,
5};

and further still on the return aspect we don't really need to create metricMeasures first, and then return it, we can do this:

1return {
2  mm: measurement * 30.48,
3  cm: measurement * 2.54,
4  meters: measurement * 91.44,
5};

so the whole function can be thinned down to:

1function convertMeasurement(measurement, unit) {
2  if (unit === "cm") {
3    return {
4      inches: measurement / 2.54,
5      feet: measurement / 30.48,
6      yards: measurement / 91.44,
7    };
8  }
9
10  return {
11    mm: measurement * 30.48,
12    cm: measurement * 2.54,
13    meters: measurement * 91.44,
14  };
15}

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co