Functions in JavaScript

Functions are group of statements that can be executed (any number of times) by calling its name.

Functions can be created using function keyword followed by function name which is again followed by a pair of parenthesis. Inside parenthesis you can pass optional arguments.

Syntax

function function_name(optional args)
{
	statement 1;
	statement 2;
}

Why to use function?

Suppose you need few statements that are used more than once. Now instead of repeating the whole statements again and again, create a function and then you just have to call the function name.

Example: Create a html file functions.htm

<!DOCTYPE html>
<html>
<head>
<title>Functions</title>
</head>
<body>
<div id="content"></div>
<script src='external.js'></script>
</body>
</html>

Now create a script file external.js

//defining function
function addition()
{
	var x = 1;
	var y = 3;
	var z = x + y;
	document.getElementById('content').innerHTML = z;
}
addition(); //function call

return keyword

functions can also return the value to the caller using return keyword.

Syntax

function function_name(optional args)
{
	statement 1;
	statement 2;
	return result;
}

Example for using for using return statement

external.js

function addition()
{
	var x = 1;
	var y = 3;
	var z = x + y;
	return z;
}
result = addition(); //function call
document.write(result);

Functions with arguments

We can pass one or more arguments inside the function. Passed arguments can be processed within the function to generate the output.

Example for using functions with arguments

external.js

function addition(x, y)
{
	var z = x + y;
	return z;
}
result =  addition(10, 11); //function call
document.write(result);

When we call the function we pass two arguments. 10 is stored in x and 11 is stored in y. Then it is processed inside the function to give the output.

<< Variables and Data Types in JavaScript Variable Scope >>