JavaScript Functions

A function is a reusable piece of code that can be called anywhere in your program. This eliminates the need to write the same code over and over again. It helps programmers to write module code. Tasks allow a programmer to divide a large program into many smaller, manageable tasks. Like any other advanced programming language, JavaScript also supports all the features required to write module code using functions. You must have seen functions like ready() and write() in previous chapters. We use these functions frequently, but they are written only once in basic JavaScript.

JavaScript also allows us to write our own relation. This section explains how to write your own function in JavaScript.

Function Definition

The most common way to define a function in JavaScript is to use the function keyword, followed by a unique function name, a parameter list (which can be empty), and a declaration block surrounded by braces.

Calling a Function

To call a function later in the script, you just write the name of the function as shown in the following code.

Function Parameters

So far, we’ve seen functions with no parameters. But various parameters can be passed when calling a function. These parameters passed into the function can be handled and any action can be performed on these parameters. A function can be separated by multiple commas.

The return Statement

This is important if you want to return value from the service. This statement must be the last statement of a function.