Setting Parameters and Arguments
Okay, now we have have simple function and statement calling it.
function addTwonumber() {
var a = 5;
var b = 10;
var result = a + b;
alert(result);
}
addTwoNumber();
That function will adding variable 'a' and 'b', assign it into variable 'result', and display the result. But it will not really useful because it's always adding the same number, 5 and 10. What if we want adding other number using this function? We can do that by defining parameter.
function addTwonumber(a, b) {
var result = a + b;
alert(result);
}
And now our function expect some parameter to passed. We can pass argument, or value we want, to the function, by writing the name of the function followed by value inside parentheses.
addTwoNumber(10, 5);
Remember, we can only passing the same amount of value that parameter of function expected. For example, you can't do this :
function addTwonumber(a, b) {
var result = a + b;
alert(result);
}
addTwoNumber(10, 5, 1); //wrong
If we want our function to pass back the result, we can use 'return'.
function addTwonumber(a, b) {
var result = a + b;
return result;
}
var result = addTwoNumber(10, 5); //result will have value of 15
Do not write anything after return statement because it will not be executed.