Google

functions

What Is a Function?

A pocket calculator performs certain functions. You push the buttons, provide information to the calculator, it performs a calculation, and returns the results. 
That's what a function does.

By definition, a function is a block of statements that performs a specific task such as  validating input, and also can return a value to the caller . A function is independent of your program and not executed until invoked by a caller. 
They are also used to break up a program into smaller units to keep it better organized and easier to maintain , and can be used over and over again and thus save you time .
 JavaScript has a large number of its own built-in functions, and you can create your own too .

when using the term method you refer to a normal function that is used with objects .

Function Declaration and Invocation


Functions must be declared before they can be used. 
To define a function, the function keyword is used, and followed by the name of the function, then a set of parentheses  () , which sometimes are used to hold parameters, values that are received by the function. The function's statements are enclosed in curly braces.

Format :


function sayHello() 
{
 alert("Hello");
}

functions are invoked by calling the function, for example :

sayHello();

 functions may have arguments :

function sayWhat(g, user) 
{
 alert(g + " " + user );

 when we call it we provide these arguments :

sayWhat("Hello", "admin");

the output is dialog box containing : Hello admin

Note : read about Scope of Variables  here 

Return Values


Functions may return values with a return statement. The return keyword is optional . A return can be used to send back the result of some task, such as a calculation, or to exit a function early if some condition occurs.

Format :


return;
return expression; 
 
 Example :
 
function sum (a, b) {
var result= a + b;
return result;
 
 
the return value can be assigned to a variable in function call 

var total=sum(1, 2);
 
the sum function is called with two arguments, 5 and 10. The sum function's return value (3) will be assigned to the variable total.



 
 

No comments: