Scripter Javascript Tutorial
javascriptmusiclogicscripterbookexcerpttutorial36 Functions
MDN: Reference: Functions
Functions are another core building block of JavaScript (and for most popular programming languages). Essentially, a function is code which is developed to perform a specific task, such as performing a calculation, and that task can be called as needed. Any time a bit of code, be it a line or a block, is repeated, then it should go into a function. The syntax for a function is very simple:
function name( argument1, argument2 ) {
// do something
}
In the above example:
Line 1: Functions are declared with the
function
statement. The function is given a name,name
in this example. Following the function name in parentheses, arguments are passed into the function. An argument is data which is passed into the function needed to perform the function’s task. Multiple arguments are separated by commas and functions with no arguments are common.Line 2: The code to be executed within the function is opened with a curly brace. Variables passed into, or created in, the function can only be manipulated in the function itself. This is called variable scope. Functions very commonly return values, such as performing a calculation which needs to be done repeatedly.
Line 3: The function is closed with a curly brace.
A very simple example is adding two numbers together:
function add( operand1, operand2 ) {
var result = operand1 + operand2;
return result;
}
var op1 = 2;
var op2 = 3;
var sum = add(op1, op2); // sum = 5
In the above example:
Line 1: A new function is declared, called
add
, which takes two arguments,operand1
andoperand2
.Line 2: The function’s code begins. A new variable
result
is declared and the two arguments are added together.Line 3: The sum is returned and the function’s code ends.
Lines 6–-7: Two values are declared.
Line 8: A new variable is declared to capture the sum and the function is called. The sum variable stores the returned value of the function.