Function return values

Photo by Joan Gamell on Unsplash

Function return values

·

2 min read

What is a return value

When starting out with functions, it can sometimes be hard to wrap your head around them. Some functions produce a return value, and others don't. Therefore, it's important to determine whether or not your function returns a value. In simpler terms, return values are the values that a function produces when it completes its execution.

// An example of a function with a return value

const favoriteFood = "My favorite fruit are watermelons";

//The new value using the replace string function 
const newString = favoriteFood.replace("watermelons", "apples");

console.log(newString); // My favorite fruit are apples
console.log(favoriteFood); // My favorite fruit are watermelons

// the string function replace() takes two arguments 
// the first is the string to be replaced 
// the second is the new string

In the above example, understanding the return value of the replace() string function is imperative to comprehend what the code does.

How to use return values

To obtain a value from your custom function, you need to use the return keyword. for example:

// The multiply function

function multiply(a, b) {
    return a * b;
}

multiply(2, 3); //6
// The above function returns the multiplication of two parameters a and b

A simple analogy that helps understand this concept is to imagine yourself baking a cake. In this process, each step of the recipe is like a function. For instance, when measuring the amount of sugar, the measurements act as return values that can be used in the next step.

In summary, a return value is the result you get after completing a task, and you can then use that value for subsequent tasks.

For documentation

MDN W3school