4) Conditionals, Loops and Functions Lesson

The Return Statement in JavaScript: Why it Matters

11 min to complete · By Ian Currie

While many functions you will write use the return statement, it's important to note that not all functions require it. The usage of return depends on the purpose of the function. This concept forms a crucial part of many programming operations and lessons, so do ensure to understand it well.

As part of this lessons, you will be building a Fahrenheit to Celsius temperature converter to give you a practical understanding of these concepts. Remember that the return statement not only sends a result back from the function but also halts the execution of the function. Furthermore, bear in mind that you can also get the result from a function in other ways such as console logging the result.

Why Is the return Statement So Useful

You'll definitely need return statements in your functions! Pay attention to the difference between the functions in the example presented in the next sections to learn why.

JavaScript Function Without a return Statement

The formula for Fahrenheit to Celsius is:

C = (F - 32) * (5 / 9)

Now you will translate this into JavaScript.

You might want to write it something like this:

let temp = 0;
let tempInF = 100;

function fToC() {
  let tempInC = (tempInF - 32) * (5 / 9);
  temp = tempInC;
}

fToC();
console.log(temp);
// OUTPUT
37.77777777777778;

This code is fine in the sense that it works, though more often than not, it will lead to confusion. Any experienced coder will immediately point out that you're creating two variables in the global scope. You do this so that the function has a value to operate on and one to store the result in. But this is unnecessary when functions can have parameters and return something.

In JavaScript, as in many programming languages, the global scope is like a big open field where everything can be seen and used by everyone. When you put something in the global scope, like a ball in the field, anyone can use that ball to play. In programming, if you write a piece of code in the global scope, any part of your program can find and use that code, just like anyone in the field can see and use the ball. But remember, if you start having lots of balls and everyone uses the same balls, it can get confusing and cause a mess, so it's important to be careful about what you place in the global scope.

Clearly, we need a better way!

JavaScript Function With a return Statement

With this in mind, you can define your function with a parameter and a return statement. You give the function something, and it gives you something back. It becomes nicely self-contained. It has clearly defined inputs and outputs:

function fToC(tempInF) {
  let tempInC = (tempInF - 32) * (5 / 9);
  return tempInC;
}

Having clearly defined inputs and outputs is always desirable for a function. It makes it easy to think about and it prevents you from creating bugs by mistake. The mathematical term for a function that will return the same output for a given input is called idempotence, but in programming you typically refer to this type of function as a pure function.

In programming, pure functions are great because they help avoid bugs by not causing unexpected changes elsewhere in the program. However, not all tasks can be done with pure functions; sometimes you need to interact with other parts of the computer, like when you save a file, or need information from the world wide web, and that's when you have to use a different kind of function.

Armed with your new and beautiful pure function, the code to convert temperature becomes a lot more elegant:

let tempInF = 40;

let tempInC = fToC(tempInF);

console.log(tempInC); // Whats the output here? Check it yourself!

Much better. But now say you wanted to go the other way. To make your temperature converter code more complete, write another function that can convert the other way. Here is the formula for converting Fahrenheit to Celsius:

F = (C * 1.8) + 32

With this formula, you can translate it to JavaScript like so:

function cToF(tempInC) {
  return tempInC * 1.8 + 32;
}

let tempInC = -10;
let tempInF = cToF(tempInC);

console.log(tempInF); // Whats the output here? Check it yourself!

Lovely, now you are armed with two self-contained pure functions to convert temperatures from Fahrenheit to Celsius and back again!

Why Are return Statements So Useful

The return statement in programming is like the grand finale of a magic trick — it's the moment when the magician reveals the result of their trick. In a program, when a function runs its course, the return statement brings out the final outcome, handing back a value to the part of the program that asked for it.

This is super useful because it lets a function do its task, like solving a math problem or finding a word in a sentence, and then give the answer so the rest of the program can use it. It's essential for communicating between different parts of a program, sharing results, and making sure that each function can complete its mission and report back.

This is why the concept of something that get's returned from a function is almost universal in programming languages. Even programming languages that don't have an explicit return statement have a mechanism for returning a value from a block of self-contained code. They allow you to create an abstraction.

Abstraction is the programmer's craft of hiding complexity to make problems easier to manage. It's like using building blocks to construct a house instead of shaping every brick by hand. Functions are the building blocks in programming, and when they return things, it's like each block is designed to perform a specific task and then pass on its creation—be it a number, a text, or something more complex—to the next block.

This hand-off between functions is essential. It allows programmers to build up layers of logic, one function at a time, without needing to know the inner workings of each part. Each returned value is a piece of a larger puzzle, and by assembling these pieces through abstraction, programmers can create intricate and powerful systems from simple, interchangeable parts.

Summary: The return Statement in JavaScript Functions

  • Functions in JavaScript don't always need a return statement; it's used when a function must send a result back.
  • A return statement ends the function's execution and provides the calling context with a value.
  • Global scope pollution is avoided by using functions that return values instead of modifying global variables.
  • Pure functions, which often use return, give consistent outputs for the same inputs and help prevent side effects in the program.
  • While pure functions are ideal for predictability, not all functions can be pure, especially those requiring external interactions.
  • The use of return is a form of abstraction, allowing complex programs to be built from simple, discrete function calls.