× Introduction Setup Environment Building blocks Built-in functions Data Types Strings Operators Conditional statements Loop statements Functions Arrays Understaing Objects Date Object Number Object Math Object String Object Window Location Navigator History DOM Basics Forms
   Programs
Basic Control Loops Functions Arrays Examples Projects Quick Ref.
   Exercises
Variables Data Types Operators Decision Loops Reeborg's World



JavaScript functions

(Reusable blocks of code)

In this tutorial you will learn javascript functions declaration and calling.

A function is a group of reusable code which can be called anywhere in your program. This eliminates the need of writing the same code again and again. It helps programmers in writing modular codes. Functions allow a programmer to divide a big program into a number of small and manageable functions.

Advantages of using functions:

  • Functions reduces the repetition of code within a program — Function allows you to extract commonly used block of code into a single component. Now you can perform the same task by calling this function wherever you want within your script without having to copy and paste the same block of code again and again.
  • Functions makes the code much easier to maintain — Since a function created once can be used many times, so any changes made inside a function automatically implemented at all the places without touching the several files.
  • Functions makes it easier to eliminate the errors — When the program is subdivided into functions, if any error occur you know exactly what function causing the error and where to find it. Therefore, fixing errors becomes much easier.

Defining and Calling a Function

Functions must be declared before they can be used. Function definitions are often stored in external JavaScript files or libraries.

To define a function, the function keyword is followed by the name of the function and a set of parentheses. The parentheses are used to hold parameters, values that are received by the function. The function’s statements are enclosed in curly braces. The function statements will be executed when they get called. JavaScript will not run the statements when the functions do not get invoked.

Syntax for declaring a function: Try It

Function definition:
function function_name () {
  //statements
}
function function_name (parameter, parameter)
{
//statements
}

Function call: Try It

function_name();
function_name(argument1, argument2, ...)

// Defining function
function sayHello() {
    alert("Hello, welcome to this website!");
}
 
// Calling function
sayHello(); // 0utputs: Hello, welcome to this website!

Once you define a function, you can use it. JavaScript functions are invoked by calling the function; for example, sayHello (). A function can be called directly from within the <script> tag, from a link, or when an event is triggered, such as when the user presses a key. When called, the function’s name is followed by a set of parentheses that may contain messages that will go to the function. These messages are called arguments.

Note: Use camelCase for naming functions. Make sure that the name describes what the function is doing.

Adding Parameters to Functions

If a user wants to send values to a function, the values are enclosed in the parentheses right after the function name and sent as a comma-separated list of arguments when the function is called. The arguments are received by the function in a list of corresponding values called parameters.

The names of the arguments are not necessarily the same names in the parameter list, but they correspond to the same values. These values can be assigned to local variables within the function. Local variables disappear when the function exits.

Syntax: Try It
function functionName(parameter1, parameter2...){ // function definition (receiver)
var result= parameter1 + parameter2;
...
} // curly braces required

functionName(argument1, argument2, ...); // function call (caller)

Example: Try It

// Defining function
function addTwoNumbers(number1, number2) {
    let total = number1 + number2;
    alert(total);
}
 
// Calling function
addTwoNumbers (3, 10); // 0utputs: 13
addTwoNumbers (12, -7); // 0utputs: 5

Set default parameters

We can specify default values to the function parameters. This means that if no arguments are provided to function when it is called these default parameters values will be used.

Example: Try It
// Defining function
function addTwoNumbers(number1=5, number2=10) {
    let total = number1 + number2;
    alert(total);
}
 
// Calling function
addTwoNumbers (); // 0utputs: 15
addTwoNumbers (2, 5); // 0utputs: 7

Return Values from a Function:

Functions can return values with a return statement. The return keyword is optional and can only exist within a function. When the return keyword is reached in a function, no further processing within the function occurs. A return can be used to send back the result of some task, such as a calculation, or to exit a function early if some condition occurs. If a function doesn’t have a return statement, it returns the undefined value.

Example: Try It

// Defining function
function addTwoNumbers(number1, number2) {
    let total = number1 + number2;
    return total;
}
 
// Calling function

let sum = addTwoNumbers (3, 10); // 0utputs: 13
alert(sum);
//alert(addTwoNumbers (3, 10));

Anonymous functions (Function Expressions)

An Anonymous function do not need to have a name and are assigned to a variable. Function expressions are convenient when passing a function as an argument to another function.

Example: Try It
let getSum = function(number1, number2) {
    let total = number1 + number2;
    return total;
};

An anonymous function can be called using the variable name, like this

Example: Try It
var sum = getSum(4,10); // sum gets the value 14

Note: There is no need to put a semicolon after the closing curly bracket in a function declaration. But function expressions, on the other hand, should always end with a semicolon.

Calling a Function from a Link.

A function can be called directly from a link, by using the JavaScript pseudoprotocol, JavaScript:, instead of a normal URL. The Java- Script: protocol and the function call are placed within quotes and assigned to the href attribute of the <a> tag. When the user clicks his or her mouse on the link, instead of the program going to the URL of another page, a JavaScript function will be called.

Example: Try It
<a href="JavaScript:greetings()"><b>Welcome!</b></a>

Calling a Function from an Event.

An event is triggered when a user performs some action, like clicking a button or moving the mouse over a link. The function assigned to the event is called an event handler. When the event is triggered, the function is called. In the following example, when the user clicks the Welcome button, the function is called.

Example: Try It
<form>
<input type="button" value="Welcome button" onClick="greetings();">
</form>