Functions in JavaScript are fundamental building blocks of code designed to
perform specific tasks. They allow for code reusability, organization, and
modularity within a program.
Defining Functions:
Functions can be defined in several ways: Function Declarations.
JavaScript Function Syntax
A JavaScript function is defined with the function keyword, followed by
a name, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same
rules as variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
Function parameters are listed inside the parentheses () in the function
definition.
Function arguments are the values received by the function when it is
invoked.
Inside the function, the arguments (the parameters) behave as local variables.
function myFunction(p1, p2) {
return p1 * p2;
}
Function Invocation
The code inside the function will execute when "something" invokes (calls) the
function:
When an event occurs (when a user clicks a button)
When it is invoked (called) from JavaScript code
Automatically (self invoked)
You will learn a lot more about function invocation later in this tutorial.