Functions in JavaScript
A function is a block of statements that perform a specific task. Functions are primarily designed for handling repetitive tasks.
A function declaration (also known as function definition or function statement) in JavaScript goes with the function
statement first, followed by a unique user-given name of the function, followed by a pair of opening/closing parentheses (may contain comma-separated parameters inside) and finally the body of the function within a pair of braces. A function always returns a value, and to return a specified value, the return
statement can be used inside the body of the function. If the return
statement is omitted, the undefined
value is returned implicitly. Execution of a function stops upon reaching the return
statement.
As an example, here we declare a function named circle
that takes in one parameter r
- the radius of a circle - and returns the computed area of a circle
function circle(r) {
var area = 3.141*r*r;
return area;
}
Instead of the hard-coded value of π (3.141), we can use the built-in JavaScript Math
object's PI
property as
function circle(r) {
var area = Math.PI*r*r;
return area;
}
To use a function, we need to call (or invoke) it. We call a function by attaching a pair of opening and closing parentheses to its name, passing comma-separated datas into the parameters inside, called arguments. For example, below we call/invoke the above declared function circle()
by passing the number 3 (radius of 3 units) as an argument
circle(3);
It computes the area of a circle of radius 3 and returns it, which is 28.274333882308138
(square units).
Function Literal Notation
We can also define the above example function (generally known as a function definition) without a name, by assigning it to a variable, as shown below
var circle = function(r) {
var area = Math.PI*r*r;
return area;
}
We can also express the above function in a compact manner with the recently introduced ES6 Arrow Function
var circle = (r) => Math.PI*r*r;
This way of defining a function is known as function literal notation, and such nameless functions are known as anonymous functions.
JavaScript is laden with pre-defined (or built-in) functions. Some examples of mostly used pre-defined functions are alert()
, setTimeout()
, setInterval()
, parseInt()
, isNaN()
, etc.
Notes
- Function names can contain alphanumeric characters, underscores and dollar signs, but they cannot start with a number.
- The number of parameters that can be passed to a function is 255.