This will log to the console the message: The function provided returned: Hello world!
Notice how we have a function call to logReturnValueOf(...)
, and the parameter in between the (
and )
is a function expression for a function that just returns the string "Hello world!". Then inside the logReturnValueOf
function, it calls its parameter with func()
, and adds the returned value to a log message.
The syntax with these uses of functions may take some time to get used to. In particular you can end up with lots of pairs of (
)
, {
and }
across different lines. However you should notice Construct's code editor, like most other coding editors, can highlight bracket pairs to help you match them up.
Returning functions
Functions can also return other functions.
You may be beginning to notice that in general, anywhere you can use a string or a number, you can also use a function. This is a useful feature of JavaScript, and is sometimes referred to as first-class functions, as functions can be treated the same as any other data type.
Here's an example of a function returning a function.
// Declare a function that returns another function
function getFunction()
{
return function()
{
console.log("Hello world!");
};
}
// Call getFunction(), which returns a function
let returnedValue = getFunction();
// Call the returned function, logging "Hello world!"
returnedValue();