Function Contents

This lesson explains the structure of a function in detail.

Return value

Here is a variation of our example program.

Press + to interact
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.

Press + to interact
// 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.

Press + to interact
function myFunction() {
// ...
// No return value
}
const result = myFunction();
console.log(result); // undefined

A ...