Function Contents
This lesson explains the structure of a function in detail.
We'll cover the following...
Return value
Here is a variation of our example program.
function sayHello() {return "Hello!";}console.log("Start of program");const message = sayHello(); // Store the function return value in a variableconsole.log(message); // Show the return valueconsole.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.
// Declare myFunctionfunction myFunction() {let returnValue;// Calculate return value// returnValue = ...return returnValue;}// Get return value from myFunctionconst 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
.
function myFunction() {// ...// No return value}const result = myFunction();console.log(result); // undefined
A ...