What is function in javascript


function are used to encapsulate code that performs a specific task. Sometimes functions are defined for commonly required tasks to avoid the repetition entailed in typing the same statements over and over . More generally, they are used to keep code that performs a particular job in one place  in one order to enhance reusability and program clarity.
   
      JavaScript function are declared with the function keywords, and the statements
that carry out their operations are listed in curly braces. Function  arguments are listed in parentheses following the function name and are separated  by commas. 
 For example:

function add (a, b)
{

var sum =  a+b;
return sum;


}

This code declares a function named  add  that adds its argument  together and  "returns"    the resulting value. The return statement tells the interpreter what value the function evaluates to. For example, you can set the value of the function equal to a variable :

var result = add(1, 2);

The arguments 1 and 2 are passed to the function , the body of  the function executes, and the result of their  addition, 3, is placed in the variable result.

   Besides passing in literal values to a function , it is also possible to pass in variables. 

For example:

var a=1, b=6;
var result;
result = add(a,b);

Experienced  programmers might ask whether it is possible to modify the values of  variables that are passed in to function. The answer is more a piece of advice : no. JavaScript employs passing by value for primitive data types,so the values of the variables a and b should remain unchanged regardless of what happens in the function add. However, other data types , notably objects, can  be changed when passed in (they are passed by reference ), making the process confusing to some. If you have programmer in other languages before, you will recognize that functions are variously called procedures, subroutines, and methods.       

Comments

Post a Comment

Popular posts from this blog

What is Operating System?

What is MAC Address?