A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.cdn.mozilla.net/en-US/docs/Learn_web_development/Core/Scripting/Return_values below:

Function return values - Learn web development

Function return values

There's one last essential concept about functions for us to discuss — return values. Some functions don't return a significant value, but others do. It's important to understand what their values are, how to use them in your code, and how to make functions return useful values. We'll cover all of these below.

Prerequisites: An understanding of HTML and the fundamentals of CSS, familiarity with JavaScript function basics as covered in the previous lesson. Learning outcomes: What are return values?

Return values are just what they sound like — the values that a function returns when it completes. You've already met return values several times, although you may not have thought about them explicitly.

Let's return to a familiar example (from a previous article in this series):

const myText = "The weather is cold";
const newString = myText.replace("cold", "warm");
console.log(newString); // Should print "The weather is warm"
// the replace() string function takes a string,
// replaces one substring with another, and returns
// a new string with the replacement made

The replace() function is invoked on the myText string, and is passed two parameters:

When the function completes (finishes running), it returns a value, which is a new string with the replacement made. In the code above, the result of this return value is saved in the variable newString.

If you look at the replace() function MDN reference page, you'll see a section called return value. It is very useful to know and understand what values are returned by functions, so we try to include this information wherever possible.

Some functions don't return any value. (In these cases, our reference pages list the return value as void or undefined.) For example, in the displayMessage() function we built in the previous article, no specific value is returned when the function is invoked. It just makes a box appear somewhere on the screen — that's it!

Generally, a return value is used where the function is an intermediate step in a calculation of some kind. You want to get to a final result, which involves some values that need to be calculated by a function. After the function calculates the value, it can return the result so it can be stored in a variable; and you can use this variable in the next stage of the calculation.

How to return a value

To return a value from a custom function, you need to use the return keyword. We saw this in action recently in our random-canvas-circles.html example. Our draw() function draws 100 random circles somewhere on an HTML <canvas>:

function draw() {
  ctx.clearRect(0, 0, WIDTH, HEIGHT);
  for (let i = 0; i < 100; i++) {
    ctx.beginPath();
    ctx.fillStyle = "rgb(255 0 0 / 50%)";
    ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
    ctx.fill();
  }
}

Inside each loop iteration, three calls are made to the random() function, to generate a random value for the current circle's x-coordinate, y-coordinate, and radius, respectively. The random() function takes one parameter — a whole number — and returns a random whole number between 0 and that number. It looks like this:

function random(number) {
  return Math.floor(Math.random() * number);
}

This could be written as follows:

function random(number) {
  const result = Math.floor(Math.random() * number);
  return result;
}

But the first version is quicker to write, and more compact.

We are returning the result of the calculation Math.floor(Math.random() * number) each time the function is called. This return value appears at the point the function was called, and the code continues.

So when you execute the following:

ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);

If the three random() calls returned the values 500, 200, and 35, respectively, the line would actually be run as if it were this:

ctx.arc(500, 200, 35, 0, 2 * Math.PI);

The function calls on the line are run first, and their return values are substituted for the function calls, before the line itself is then executed.

Implementing function return values

Let's have a go at writing some functions featuring return values.

  1. Make a local copy of the function-library.html file from GitHub. This is a simple HTML page containing a text <input> field and a paragraph. There's also a <script> element, in which we have stored a reference to both HTML elements in two variables. This page will allow you to enter a number into the text box, and display different numbers related to it below.

  2. Add some useful functions to this <script> element below the two existing lines:

    function squared(num) {
      return num * num;
    }
    
    function cubed(num) {
      return num * num * num;
    }
    
    function factorial(num) {
      if (num < 0) return undefined;
      if (num === 0) return 1;
      let x = num - 1;
      while (x > 1) {
        num *= x;
        x--;
      }
      return num;
    }
    

    The squared() and cubed() functions are fairly obvious — they return the square or cube of the number that was given as a parameter. The factorial() function returns the factorial of the given number.

  3. Include a way to print out information about the number entered into the text input by adding the following event handler below the existing functions:

    input.addEventListener("change", () => {
      const num = parseFloat(input.value);
      if (isNaN(num)) {
        para.textContent = "You need to enter a number!";
      } else {
        para.textContent = `${num} squared is ${squared(num)}. `;
        para.textContent += `${num} cubed is ${cubed(num)}. `;
        para.textContent += `${num} factorial is ${factorial(num)}. `;
      }
    });
    
  4. Save your code, load it in a browser, and try it out.

Here are some explanations for the addEventListener() function in step 3 above:

Note: If you have trouble getting the example to work, check your code against the finished version on GitHub (see it running live also).

Add some functions of your own!

At this point, we'd like you to have a go at writing out a couple of functions of your own and adding them to the library. How about the square or cube root of the number? Or the circumference of a circle with a given radius?

Some extra function-related tips:

Test your skills!

You've reached the end of our set of functions articles, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Functions.

Conclusion

So there we have it — functions are fun, very useful, and although there's a lot to talk about in regards to their syntax and functionality, they are fairly understandable.

If there is anything you didn't understand, feel free to read through the article again, or contact us to ask for help.

Next, we'll move on to look at events in more detail.

See also

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4