Function
Info:
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).
The code to be executed, by the function, is placed inside curly brackets:
{}
function myFunction(p1, p2) {
return p1 * p2;
}Syntax
defined with the
function
keyword, followed by aname
, followed by parentheses()
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
Function
arguments
are the values received by the function when it is invoked.Inside the function, the
arguments
(the parameters) behave as localvariables
.function name(parameter1, parameter2, parameter3) {
// code to be executed
}
Invocation, function will execute when...
- an event occurs (buttonClick)
- called from JavaScript code
- automatically (self invoked)
return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":
// Function is called, the return value will end up in x
let x = myFunction(4, 3);
function myFunction(a, b) {
// Function returns the product of a and b
return a * b;
}
Used as Variable Values
Instead of using a variable to store the return value of a function:
let x = toCelsius(77);
let text = "The temperature is " + x + " Celsius";You can use the function directly, as a variable value:
let text = "The temperature is " + toCelsius(77) + " Celsius";
Local Variables
Variables declared within a JavaScript function, become LOCAL to the function.
Local variables can only be accessed from within the function.
// code here can NOT use carName
function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}
// code here can NOT use carNameSince local variables are only recognized inside their functions, variables with the same name can be used in different functions.
Local variables are created when a function starts, and deleted when the function is completed.
Danger:
Accessing a function with incorrect parameters can return an incorrect answer:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
let value = toCelsius(); // missing parameterAccessing a function without
()
returns thefunction
and not thefunction result
:function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
let value = toCelsius;
// returns: function toCelsius(f) { return (5/9) * (f-32); }