The terms call, invoke, and execute (as well as run) are interchange‐
able, and I will use each in this book to get you comfortable with
them all. In certain contexts and languages, there may be subtle dif‐
ferences between these terms, but in general use, they are equiva‐
lent.
Return Values
Calling a function is an expression, and as we know, expressions resolve to a value. So
what value does a function call resolve to? This is where return values come in. In the
body of a function, the
return
keyword will immediately terminate the function and
return the specified value, which is what the function call will resolve to. Let’s modify
our example; instead of writing to the console, we’ll return a greeting:
function
getGreeting
() {
return
"Hello world!"
;
}
Now when we call that function, it will resolve to the return value:
getGreeting
();
// "Hello, World!"
If you don’t explicitly call
return
, the return value will be
undefined
. A function can
return any type of value; as a reader’s exercise, try creating a function,
getGreetings
,
to return an array containing “Hello, World” in different languages.
Calling Versus Referencing
In JavaScript, functions are objects, and as such, can be passed around and assigned
just like any other object. It’s important to understand the distinction between calling
a function and simply referencing it. When you follow a function identifier with
parentheses, JavaScript knows that you’re calling it: it executes the body of the func‐
tion, and the expression resolves to the return value. When you don’t provide the
parentheses, you’re simply referring to the function just like any other value, and it’s
not invoked. Try the following in a JavaScript console:
getGreeting
();
// "Hello, World!"
getGreeting
;
// function getGreeting()
Being able to reference a function like any other value (without calling it) allows a lot
of flexibility in the language. For example, you can assign a function to a variable,
which allows you to call the function by another name:
const
f
=
getGreeting
;
f
();
// "Hello, World!"
104 | Chapter 6: Functions