In JavaScript, programs execute one line at a time from top to bottom.
Functions allow you to re-use bits of code to repeat a computation to return an output given 0 or more inputs.
Consider the following:
var a = 1;
bar b = 2;
// Get the sum of a and b
var c = a + b;
// New calculation
var c = 2;
var d = 4;
// Get the sum of c and d
var e = 2 + 4;
Now lets use a function
function sumNumbers(a, b) {
return a + b;
}
// First calculation
var a = sumNumbers(1, 2)
var b = sumNumbers(2, 4)
Take a good look at this. There is a lot going on so let's break down what is going on.
A function is declared with the function
keyword followed by the name of the function - similar to a variable
at this point.
We then must open parenthesis and define our inputs
. We can put in 0 or more inputs.
The inputs are scoped
locally to this function only. This means that in the above example, within the function named sumNumbers
, input a
and input b
have no bearing on any code that is not within the curly braces (the block
) of the function.
Once we have defined the inputs, we open the function by typing in curley brances.
We then perform our logic on the inputs or do some code
we then send our output
using the return
keyword to the thing that called the function.
To call a function, we type the name of the pre-defined function (in this case sumNumbers
) followed by parenthesis where we put in the values for the inputs
.
When calling a function that expects inputs, you pass in a variable
or raw value like in the example.
The name of the input
variables when calling a function and the name of the input
on the funciton itself are seperate and do not clash. You can use different names, or you can use variables with the same name.