A JavaScript function is a block of code that is made to do a task. Functions can be called over and over again to reuse the same code. There are two types of functions, ones you create yourself and others that are built in. Going back to the alert box, alert() is a premade built in function. Let’s create a function that takes 2 numbers and then outputs them in an alert box. First we create the function by using the word function and giving it a name. Then we put in the variables into parenthesis(). Not all functions will take variables though, so empty parenthesis are possible as well. Just like in math, variables take the place of constants, such as strings or literals and numbers. After the parenthesis, we block out the function with curly braces {}.
function addNumbers(variable1, variable2)
{
}
That is the basic setup of a function. Now let’s call it and make it alert the two variables being added together.
function addNumbers(a, b)
{
alert(a+b);
}
addNumbers(2, 3);
Sometimes you will want to have the function end before the end. We will get into if statements in a future tutorial, but that is one way a function would return early. In order to end a function, we would use the return keyword.
function addNumbers(a, b)
{
return alert(a+b);
}
addNumbers(2, 3);
Sometimes you will want a variable to have a default value. You are able to do this by setting a default value when you create the function.
function addNumbers(a=1, b=5)
{
return alert(a+b);
}
addNumbers(2);
In the above example, the default value of a is 1 and b is 5. Because we pass in a, the default value is ignored, but b is still set to default. The alert box would display 6.