JavaScript Functions

In Javascript, a function is a block of code that is designed to perform a task. Instead of copying the code everywhere the task needs to be performed, functions let you reuse the block of code by writing once and using it many places.

A function is invoked when another part of code calls that function by its name followed by any parameter values as defined by the function.

	function myFunction(p1, p2) {
		return p1 * p2;              
                //  returns the product of p1 and p2
	}

Function Syntax

Every function starts with function keyword, followed by function name, followed by parenthesis. Function name can contains alphanumeric characters, underscore(_) and dollar sign. Extra parameters can be passed to function call within parenthesis. Multiple parameter can be passed with comma separated values.
The function code is written within { } brackets.

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

parameter1, parameter2, parameter3 are function parameters. Values of these parameters are called arguments of function. Parameters have local scope within function

Function call

Code within function will execute when something calls that function:

  • When any event occurs (click event, move event)
  • When called from within Javascript
  • Automatic

Function Return

A function can have a return value. A function can have more than one return statement. A function execution stops once it reaches the first return statement. Once return statement is executed, Javascript returns back to the next statement from where function is being called.

Below function will multiply 2 numbers.

<!DOCTYPE html>
<html>
<body>

<p>This example calls a function which performs a calculation, and returns the result:</p>

<p id="demo"></p>

<script>
function multiply(a, b) {
    return a * b;
}
document.getElementById("demo").innerHTML = multiply(4, 3);
</script>

</body>
</html>

Download the code Run the code

The result in x will be: 12

Benefits of functions

Generally functions are used to group together related code. Functions are write once, use many times.
Same function can be used multiple time with different arguments which produces different output.

<!DOCTYPE html>
<html>
<body>

<p>This example calls a function which performs a square of given number, and returns the result:</p>
<p id="demo"></p>

<script>
function square(num) {
    return num * num;
}
document.getElementById("demo").innerHTML = square(4);
</script>

</body>
</html>

Download the code Run the code

The () Operator calls the Function. when function name is written without (), it refers to function object. when function name is written with (), it returns function result.

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .