JavaScript functions are reusable blocks of code that perform a specific task, taking some form of input and returning an output.
To define a function, you must use the function keyword, followed by a name, followed by parentheses ( ).Then you have to write the function logic between curly brackets { }
Here is an example of how to write a function in JavaScript:
function addTwoNumbers(x, y) {
return x + y;
}
- “Function” is the keyword required to actually start declaring a function
- “addTwoNumbers” is the function’s name, which is customizable. Function names can contain letters, numbers, and certain special characters, just like variables.
- (x, y) are parameters, which are variable names for the inputs the function will accept. These parameters are also referred to as arguments.
- “Return” is the keyword that exits the function and shares an optional value outside
- The code that the function will execute must be put inside of curly brackets { }
Once a JS function is defined (declared), you can use it by referencing its name with parentheses ( ) right after. Note that a function doesn’t have to have parameters – they can simply be left blank in the parentheses:
// EXAMPLE
function greetThePlanet() {
return "Hello world!";
}
greetThePlanet();
// OUTPUT
"Hello world!"
If a function does have parameters, you’ll need to provide values inside the parentheses when using the function:
// EXAMPLE
function square(number) {
return number * number;
}
square(16);
// OUTPUT
256
In the example above, you have to provide a number inside of the parentheses in order for the function to work and to receive a proper output. Otherwise, your code won’t work and you’ll get an error message.
If your function takes more than one argument, simply separate them with a comma inside of the parentheses. You can refer to the “addTwoNumbers” function at the top of this page for an example.