Search⌘ K

Function Contents

Explore how to use return statements in JavaScript functions to send back values, manage local variables within functions for scoped data, and define parameters to create adaptable and reusable functions. This lesson helps you write more organized and independent code blocks.

Return value

Here is a variation of our example program.

Javascript (babel-node)
function sayHello() {
return "Hello!";
}
console.log("Start of program");
const message = sayHello(); // Store the function return value in a variable
console.log(message); // Show the return value
console.log("End of program");

Run this code, and you’ll see the same result as before. In this example, the body of the sayHello() function has changed: the statement console.log("Hello!") was replaced by return "Hello!". The keyword return indicates that the function will return a value, which is specified immediately after the keyword. This return value can be retrieved by the caller.

Javascript (babel-node)
// Declare myFunction
function myFunction() {
let returnValue;
// Calculate return value
// returnValue = ...
return returnValue;
}
// Get return value from myFunction
const result = myFunction();
// ...

This return value can be of any type (number, string, etc). However, a function can return only one value. Retrieving a function’s return value is not mandatory, but in that case the return value is “lost”. If you try to retrieve the return value of a function that does not actually have one, we get the JavaScript value undefined.

Javascript (babel-node)
function myFunction() {
// ...
// No return value
}
const result = myFunction();
console.log(result); // undefined

A function ...