JavaScript – Function

A function is a group of code designed to perform a particular task and can executed when they are called. It helps to write a modular codes. Functions allow a programmer to divide a big program into a number of small and manageable functions. We can call functions again and again when needed, but they had been written only once.

Function Definition Syntax

In JavaScript function is defined with function keyword, followed by a name and parentheses ().

Function names can contain letters, digits, underscores, and dollar signs.

The parentheses may include parameter names separated by commas: (parameter_1, parameter_2)

Code is to be executed by the function, is placed inside curly brackets: {}

function function_name(parameter1, parameter2, parameter3) {
//code to be executed
}

Example of Simple function (without parameters)

<script>
function hello() { // function defined
alert(“Hello User”);
}
hello(); //function called
</script>

Calling a Function

Function can also be invoke later in the script, Let’s take an example:

<html>
<head>
<script>
function helloUser() {
document.write (“Hello User”);
}
</script>
</head>
<body>
<p>Click the below Button to call the function</p>
<input type = “button” onclick = “helloUser()” value = “Click Me”>
</body>
</html>

Function Parameters

We can pass arbitrary data to functions using parameters, these parameters can be captured and manipulate inside the function.

We can pass multiple parameters to function by comma separated.

Example:

<html>
<head>
<script>
function sum(i, j) {
document.write (“Sum of i and j is “+(i+j));
}
</script>
</head>
<body>
<p>Click the below button to call the “sum” function</p>
<input type = “button” onclick = “sum(8,6)” value = “SUM”>
<p>You can try with different parameters inside the function.</p>
</body>
</html>

Function Return

return is a optional statement in JavaScript function, this required if we want to return a value from a function. When JavaScript reaches a return statement, the function stop execution.

Example:

<html>
<head>
<script>
function sum(i, j) {
var s;
s = i + j;
return s;
}
function avg() {
var result;
result = sum(8, 9)/2;
document.write (result );
}
</script>
</head><body>
<p>Click the below button to call the function “avg”</p>
<form>
<input type = “button” onclick = “avg()” value = “Get Average”>
</form>
<p>You can try with different parameters inside the function.</p>
</body>
</html>


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.