Returning a value from a function!
How to get the result of a function to be used in other operations?
Syntax:function name(parameter 1,parameter 2,...)
// set of statements that will be executed
A function can also return a value
after doing the specified operations. To explain, we would consider a requirement where we have to calculate x2
We will calculate x2
in a function and return the result of x2
. After getting the return value, we will divide it by 2.
var c = number1*number1;
// Now we will return the result
var x = 4;
// Here we invoke the function and capture the result
var des = square(x);
var res = des/2;
document.write(" The result - "+res);
The result - 8
In the above example we calculate x2
in the function "square(xxx)". We returned the result.Getting the Result:
As the function is to return a value, while we invoke the function we assigned a variable to capture the result as "var des =
Now the result of x2
is assigned to the variable des.
Using the variable 'des' further operations were completed.
Note: Once the return statement is called in a function it will break, i.e no further statements below it will be executed.