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.

To return a value from a function:

1.
var newNum = colBasis + getNewNum() + 1;



This 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.


Script 3.7. A function can return a value, which can then be checked.
window.onload = initAll;

function initAll() {
     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,0,0,0,0,1,1,1,1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,4);
     var colBasis = colPlace[thisSquare] * 15;
     var newNum = colBasis + getNewNum() + 1;

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

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

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.45.153