Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Podia.

return statement – JavaScript

Summary

To create a function in JavaScript, use the function keyword.

Details

A function allows you to group one or more lines of code together and give the group of code a name. You can then reuse this group of code whenever you need to by writing the function name (with parentheses).

return keyword

Functions can also return values. This means that you can take the value produced by a function and use it in other parts of your program. For example, you can store the value returned by a function inside of a constant or variable. To return a value, use the return keyword:

function myFunction() {
  const someValue = "Hello world";  
  return someValue;
}

// Call function
const myConstant = myFunction(); // myConstant will now equal "Hello world"

The return keyword can be used with functions with and without parameters. Here’s an example of a function with parameters:

function myOtherFunction(num1, num2) {
  return num1 + num2;
}

const myConstant = myOtherFunction(1, 2); // myConstant will now equal 3

Demo

Exercises

Try the following statements in the console:

function myOtherFunction(num1, num2) {
  return num1 + num2;
}

myOtherFunction(1, 2)

The output should be 3.

References

function declaration on MDN

Back to: JavaScript Reference > JS Functions