Summary: in this tutorial, you will learn about the JavaScript functions that allow you to structure your code into smaller and more reusable units.
When you write a program, you often need to perform the same action in many places. For example, you want to show a message to the users when they complete an action.
To avoid repeating the same code all over places, you can use a function to wrap that code and reuse it.
JavaScript provides many built-in functions such as alert() and console.log(). In this tutorial, you will learn how to develop custom functions.
Declaring functions
To declare a function, you use the function keyword, followed by the function name, a list of parameters, and the function body as follows:
function functionName(parameters) {
// function body
// ...
}Code language: JavaScript (javascript)The function name must be a valid JavaScript identifier. By convention, the function name should start with a verb like getData(), fetchContents(), or isValid().
A function can accept zero, one, or multiple parameters. If there are multiple parameters, you need to separate them by commas (,).
The following declares a function named say() that accepts no parameter:
function say() {
//...
}Code language: JavaScript (javascript)The following declares a function named square() that accepts one parameter:
function square(a) {
//...
}Code language: JavaScript (javascript)And the following declares a function named add() that accepts two parameters:
function add(a, b) {
// ...
}Code language: JavaScript (javascript)Inside the function body, you can implement the logic. For example, the following say() function simply shows a message to the console:
function say(message) {
console.log(message);
}Code language: JavaScript (javascript)In the body of the say() function, we call the console.log() function to output a message to the console.
Calling functions
To call a function, you use its name followed by the function arguments enclosed in parentheses, like this:
functionName(arguments);Code language: JavaScript (javascript)When you call a function, the function executes the code inside its body. This process is also known as invocation. In other words, you call a function or invoke a function to execute it.
For example, the following shows how to call the say() function:
say('Hello');Code language: JavaScript (javascript)The 'Hello' string is an argument that we pass into the say() function.
Parameters vs. Arguments
The terms parameters and arguments are often used interchangeably. However, they are essentially different.
The parameters are used when declaring the function. For example, in the say() function, the message is the parameter.
On the other hand, the arguments are values the function receives from each parameter at the time the function is called. In the case of the say() function, the 'Hello' string is the argument.
Returning a value
Every function in JavaScript returns undefined, unless otherwise specified. See the following example:
function say(message) {
console.log(message);
}
let result = say('Hello');
console.log('Result:', result);Code language: JavaScript (javascript)Output:
Hello
Result: undefinedCode language: JavaScript (javascript)To specify a return value for a function, you use the the return statement followed by an expression or a value, like this:
return expression;Code language: JavaScript (javascript)For example, the following add() function returns the sum of the two arguments:
function add(a, b) {
return a + b;
}Code language: JavaScript (javascript)The following shows how to call the add() function:
let sum = add(10, 20);
console.log('Sum:', sum);Code language: JavaScript (javascript)Output:
Sum: 30Code language: HTTP (http)The following example shows how to use multiple return statements in the function to return different values based on conditions:
function compare(a, b) {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
return 0;
}Code language: JavaScript (javascript)The compare() function compares two values. It returns:
- -1 if the first argument is greater than the second one.
- 1 if the first argument is less than the second one.
- 0 if the first argument equals the second one.
The function immediately stops executing when the return statement is reached. Therefore, you can use the return statement without a value to exit the function prematurely, like this:
function say(message) {
// show nothing if the message is empty
if (! message ) {
return;
}
console.log(message);
}Code language: JavaScript (javascript)In this example, if the message is blank (or undefined), the say() function will show nothing.
The function can return a single value. If you want to return multiple values from a function, you need to pack these values in an array or an object.
The arguments object
Inside the body of a function, you can access an object called arguments that represents the named arguments of the function.
The arguments object behaves like an array though it is not an instance of the Array type.
For example, you can use the square bracket [] to access the arguments: arguments[0] returns the first argument, arguments[1] returns the second one, and so on.
Furthermore, you can use the length property of the arguments object to determine the number of arguments.
The following example implements a generic add() function that calculates the sum of any number of arguments.
function add() {
let sum = 0;
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}Code language: JavaScript (javascript)Hence, you can pass any number of arguments to the add() function, like this:
console.log(add(1, 2)); // 3
console.log(add(1, 2, 3, 4, 5)); // 15Code language: JavaScript (javascript)Function hoisting
In JavaScript, it is possible to use a function before it is declared. See the following example:
showMe(); // a hoisting example
function showMe(){
console.log('an hoisting example');
}Code language: JavaScript (javascript)This feature is called hoisting.
The function hoisting is a mechanism that the JavaScript engine physically moves function declarations to the top of the code before executing them.
The following shows the version of the code before the JavaScript engine executes it:
function showMe(){
console.log('a hoisting example');
}
showMe(); // a hoisting exampleCode language: JavaScript (javascript)Summary
- Use the
functionkeyword to declare a function. - Use the
functionName()to call or invoke a function to execute it. - A function implicitly returns
undefined, use thereturnstatement to explicitly specify the return value for the function. - The
argumentsis an object that is accessible only inside the function body. It represents the arguments of the function. - The function hoisting allows you to place the call to the function before the function declaration.