JavaScript Functions

A JavaScript function is a unit for code or statements which performs a specific task. In other programming languages such block of statements is called subroutine,function or method. But in JavaScript we usually called it as function.

The code inside the function will execute when "something" invokes (calls) the function:

A general syntax for function is written as below

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



A JavaScript functions starts with a keyword function then followed by Function Name and an optional list of parameters  and block of statements is enclosed in parenthesis.

For Example a below functions adds two numbers and returns the results to its calling program.

function AddNumbers(num1,num2)
{
 return num1+num2;
}  


How to use call or use a function.


One function is declared then it can be called or invoked from anywhere using


  • When an event occurs (when a user clicks a button)
  • When it is invoked (called) from JavaScript code
  • Automatically (self invoked)

For example look at below example.


Above code listing defines a functions

function myFunction(a, b) {
  return a * b;
}


code below calls or invokes the myFunctions as 

var x = myFunction(4, 3);


and product of 4 and 3 is written in HTML as 12 as shown 

Function Return

When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":

Local Variables

Variables declared within a JavaScript function, become LOCAL to the function.
Local variables can only be accessed from within the function.

Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.
Local variables are created when a function starts, and deleted when the function is completed.

Advantages of using Funtions


You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce different results.