Functions are blocks of code that perform specific tasks. In JavaScript, as in other languages, a function needs to be invoked to run its code. Functions don’t take up space in memory unless they are invoked.
The syntax for functions in JavaScript can be something like the following:
function mul(x, y) {
return x * y;
}
This function multiples the numbers x and y. In this case, x and y are function arguments, or the variables that are passed in and defined every time the function is called. When we invoke the function, which is covered later in this article, we define, or pass, the values that we want to have multiplied.
JavaScript functions are defined using the function keyword, followed by the name of the function. Make sure to avoid using language-specific keywords like var or function when you name your function, but aside from that restraint the name can rather contain letters, digits, and underscores just like variable names. A pair of parentheses follows the function’s name. They can be empty, or they can have the function’s arguments inside.
Once you have closed the parentheses, the next step is a pair of curly brackets. These brackets contain the function’s body, which is the code that will be executed when the function is invoked.
There are two types of function: void functions and return type functions. Void functions don’t return anything. Instead, they just execute the code inside the function, which may or may not affect global variables (variables defined in other parts of the code). Return type functions return a certain value at the end, like the product of two numbers.
After the function is executed, the code returns to the line that called the function. It may or may not have a return value.
Functions have many benefits like reusability. You can easily pass the code for functions to others, who can use the function without looking at the code it contains. This phenomenon is sometimes called a black box since the code simply works when you know the correct input and output parameters. Excited about functions and ready to try one of your own? Join Robogarden. Register today for free.