What are Functions in JavaScript?
Introduction
There are occasions when you would like to bundle a group of code so that it is reusable, and functions give this feature in JavaScript as well as other programming languages.
Simply put, A JavaScript function is a block of code designed to perform a particular task.
Creating functions has many advantages:
- Code reuse: Define the code once, and use it many times.
- Easily accept and process input parameters
- Quickly add functionality to your website
- Use the same code many times with different arguments, to produce different results.
JavaScript Function Syntax
A JavaScript function is defined with the following:
- function keyword
- followed by the name of the function,
- then by parentheses ( ) (which can take in parameters, or also be left empty).
- the body of the function which is wrapped in curly braces { }
Example:
function myFunction() {
//code to be executed
}
In the above example, the function name is written using camelCase which is a naming convention in computer programming.
Function names can contain:
- letters (A-Z)
- digits (1-9)
- underscores (_)
- and dollar signs ($)
- (the same rules as variables)
Function parameters are the names listed in the function definition.
Function arguments are the real values passed to (and received by) the function when you call it.
So the syntax for declaring a function with parameters will look like this (The parentheses may include parameter names separated by commas):
function myFunction(parameter1, parameter2){
//function body ...
}
And to invoke it or call the function:
myFunction(argument1, argument2)
The code to be executed, by the function, is placed inside curly brackets: {}
Example:
function myFunction(parameter1, parameter2 ) {
//code to be executed ...
}
Calling a Function
You must call the function in order for it to be executed.
To call a function, begin with the function name, followed by parentheses, which can take in arguments.
Example:
function myFunction() {
console.log("Calling a Function!");
}
myFunction();
//Alerts "Calling a Function!"
Function Return
A return statement is an optional part of a function. It is used to return the function’s result.
This statement is in handy when performing calculations that require a result.
The function terminates execution when it reaches a return statement in JavaScript.
Example:
function myFunction(a, b) {
return a * b; // Function returns the product of a multiplied by b
}
myfunction(10, 20) // To invoke this function, we call it like this.
//output
200
Conclusion
This article taught you about JavaScript functions and how to write your own.
You can structure your code by putting everything into separate blocks that execute different jobs with functions. There is a lot more to learn about functions. A great resource that goes in to further detail is on MDN Web Docs – Functions
Share this article. Follow me on Twitter for more updates.