Previous Page
Next Page

Working with Functions That Return Values

Up to this point, all the functions that you've seen simply do something and then return. Sometimes, though, you want to return a result of some kind. Script 3.7 makes the overall script more understandable by breaking out some of the calculations in previous examples into a function which returns the random numbers for the cells on the Bingo card. Another function then uses this result.

Script 3.7. A function can return a value, which can then be checked.

window.onload = newCard;

function newCard() {
     if (document.getElementById) {
        for (var i=0; i<24; i++) {
           setSquare(i);
        }
     }
     else {
        alert("Sorry, your browser doesn't support this script");
     }
}

function setSquare(thisSquare) {
     var currSquare = "square" + thisSquare;
     var colPlace = new Array(0,1,2,3,4,0,1,2,3, 4,0,1,3,4,0,1,2,3,4,0,1,2,3,4);
     var colBasis = colPlace[thisSquare] * 15;
     var newNum = colBasis + getNewNum() + 1;

     document.getElementById(currSquare). innerHTML = newNum;
}

function getNewNum() {
     return Math.floor(Math.random() * 15);
}

To return a value from a function:

1.
var colBasis = colPlace[thisSquare] * 15;
var newNum = colBasis + getNewNum() + 1;



The first line is just a little bit of cleanup, in that we've calculated it in the last task; now, we're instead assigning it to a variable that we'll use in the second line.

The second line is again just setting the newNum variable to our desired number, but here we've moved that random number generator into a function, called getNewNum(). By breaking the calculation up, it makes it easier to understand what's going on in the script.

2.
function getNewNum() {
  return Math.floor(Math.random() * 15);
}



This code calculates a random number between 0 and 14 and returns it. This function can be used anywhere a variable or a number can be used.

Tip

  • Any value can be returned. Strings, Booleans, and numbers work just fine.



Previous Page
Next Page