A JavaScript function is a block of code designed to perform a particular task. It is executed when "something" invokes it (calls it).
A function is defined with the function keyword, followed by a
name, followed by parentheses ().
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
The code inside a function is not executed until it is invoked. A function can be invoked when:
When JavaScript reaches a return statement, the function will stop executing.
If the function was called from a statement, JavaScript will "return" to execute the code
after the invoking statement.
let x = myFunction(4, 3); // Function is called, return value will be stored in x
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
The () operator invokes the function. Accessing a function without
() will return the function definition instead of the function result.
function toCelsius(f) {
return (5/9) * (f-32);
}
let value = toCelsius(77); // Invokes the function
let definition = toCelsius; // Returns the function object
return statement sends a value back to the caller
() operator