JavaScript Function Exercises
For introduction to JavaScript presentation.
by Matt Swensen
JavaScript
//////////////////////////////////////////
// Excercise 1: Functions as Parameters //
//////////////////////////////////////////
// Below is a function takes a function as its
// third parameter. Because of this, it is considered
// a "higher-order" function. It does some calculations
// and then invokes the function passed to it, giving
// said function the results of the calculations as
// parameters.
function divide(a, b, callback) {
var quot = Math.floor(a / b),
rem = a % b;
callback(quot, rem);
}
// Try it: invoke divide() with two integers and an
// anonymous function as parameters.
divide(4123, 14, function(q, r) {
print('The quotient is: ' + q);
print('The modulus is: ' + r);
});
/////////////////////////////////////////////
// Excersize 2: Functions as Return Values //
/////////////////////////////////////////////
// Just as functions can be passed as parameters,
// they can be returned from other functions as well.
// Write a function with signature `getRandomGenerator(a, b)`
// that returns a function that will return a random number
// between the two numbers a and b. I have written 2 lines
// that invoke your function so you can see how it is supposed
// to work.
function getRandomGenerator(a, b) {
return function() {
return Math.floor(Math.random() * (b - a + 1) + a);
};
}
// Un-comment these when your function is ready.
var getRandomBetween1and10 = getRandomGenerator(1, 10);
print('Random int between 1 and 10: ' + getRandomBetween1and10());
// Something to take note of: see how the function you are
// returning has reference to the arguments passed to
// getRandomGenerator? This principle is called "closure."
////////////////////////////////////
// Excersize 3: Function Contexts //
////////////////////////////////////
// In JavaScript, functions are objects. Just like any object,
// therefore, functions have methods. Two handy ones are call()
// and apply(). They allow you to choose the...