Functions allow the encapsulation of statements.
Functions in Javascript are declared using the function
keyword,
followed by arguments and the function body.
The basic syntax is as follows:
function functionName(arg0, arg1,...,argN) {
statements
}
Here's an example. This function is called using its name, followed by the function arguments enclosed in parentheses and separated by commas in case of multiple arguments.
function sayHi(name, message) {
console.log("Hello " + name + ", " + message);
}
sayHi("Javascript", "is it working?");
The code above generates the following result.
Functions can return a value using the
return
statement followed by the value to return.
function sum(num1, num2) { return num1 + num2; } var result = sum(5, 10); console.log(result);
The code above generates the following result.
A function stops executing and exits immediately when it encounters the return statement. Therefore, any code after a return statement will never be executed. For example:
function sum(num1, num2) {
return num1 + num2;
console.log("Hello world"); //never executed
}
var result = sum(5, 10);
console.log(result);
The code above generates the following result.
It's also possible to have more than one return statement in a function, like this:
function diff(num1, num2) {
if (num1 < num2) {
return num2 - num1;
} else {
return num1 - num2;
}
}
var result = diff(5, 10);
console.log(result);
The code above generates the following result.
The return statement can be used without return value, and will return undefined
.
function sayHi(name, message) {
return;
console.log("Hello " + name + ", " + message); //never called
}
var result = sayHi(5, 10);
console.log(result);
The code above generates the following result.
Strict mode places several restrictions on functions:
A recursive function is a function which calls itself by name.
arguments.callee
is a pointer to the function being executed and, as such, can be used
to call the function recursively
function factorial(num){
if (num <= 1){
return 1;
} else {
return num * arguments.callee(num-1);
}
}
The value of arguments.callee is not accessible to a script running in strict mode. In strict mode, you can use named function expressions to define recursive functions
var factorial = (function f(num){
if (num <= 1){
return 1;
} else {
return num * f(num-1);
}
});