Functions


"Functions are very important method for a programing language, so please learn it carefully yet they are not very difficult if can understand by logics. Learn functions step by step very care fully don't be afraid they are very easy."

In simple term we can say functions are reusable codes which we can use multiple times and anywhere in web-page, this depends on developer needs. Functions use some functionality of scopes which we learn in next lesson, now just focus on functions.

We can make or store function into variables by using var keyword and just give a var name to function.

Always remember that in function body we must have to use return keyword, for return implied parameters another function not going to work. We also can use alert or console.log window keyword but return keyword is always best to use. Use return method from inside the function body and display result with alert,console.log, prompt, confirm (Window default keywords) whatever you use from outside the function.


Syntax of function :

function function-name( parameter 1, parameter 2,...parameter n ) {
return ( parameter 1 , parameter 2, ...parameter n );
}
function-name(passing values of parameters);

Some examples of functions:

Make a sum function for who can do sum for two values a and b

function sum ( a , b ) {
return( a + b );
}
alert( sum ( 2, 3 ) );

// Creating a function for sum of two parameters a and b.
// Return the parameters with action(Sum).
// Closing the function body
// Put the values of parameters into sum function.and also show the result by using alert function.

We implied here two parameters and give two values a = 2 and b = 3 so here we get result 5 by using sum function.

How can store function into a variable? Let see an example.

var Multiply = function(a,b){
return( a * b );
}
console.log(Multiply (2,3));

There is nothing change by using var, all functionality of function are same. We are just store function into var keyword.

I think Hope fully you are thinking here that why i need to create a function for Sum or Multiply of 2 and 3. ? But what about in multiple conditions and multi tasking? Let see an another example.

Creating a calculator function for two parameters.

function cal( v1, v2, fn){
return fn(v1,v2);
}
function sum(v1,v2){
return v1 + v2;
}
function min(v1,v2){
return v1-v2;
}
function mul(v1,v2){
return v1 * v2;
}
function div(v1,v2){ //We can also use here different parameters.
return v1/v2;
}
console.log("Value1 = " +40);
console.log("Value2 = " +20);
console.log("Value1 + Value2 = "+(cal (40,20,sum)));
console.log("Value1 - Value2 = "+(cal (40,20,min)));
console.log("Value1 * Value2 = "+(cal (40,20,mul)));
//We can also use different parameters for passing our values into semi functions.


Wconcert India © 2015   ·   All Rights Reserved

Free Web Hosting