Processing Function Output
2. Printing a function output
To print an output of a function, we can use the different I/O statements discussed in Module 8.4 (Basic Statements: I/O Statements). Suppose that we have a code of a function that computes the sum of two numbers below. The output of this function is the sum of the two inputs.
function getSum(a, b){
sum = a + b;
}
If we want to print the sum of the two numbers, we can do so by adding an I/O statement within the
function block. The code below shows an example of printing the sum inside an HTML element.
<div id="div1"> </div>
<script>
function getSum(a, b){
sum = a + b;
document.getElementById('div1').innerHTML = sum;
}
getSum(1,2);
</script>
This next block of code shows how to display the output of the function using an alert box.
<script>
function getSum(a, b){
sum = a + b;
window.alert(sum);
}
</script>
With the two methods learned, notice that the output is accessed only within the function block.
Remember that variables created inside the function block are local variables – this means that they can only
be accessed within that block. When you try to access that variable outside the function, it will give an
undefined value.