JavaScript Function Exercises

For introduction to JavaScript presentation.

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(5234, 78, function(q, r) {
    print('The Quotient is: ' + q);
    print('With Remainder: ' +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.

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(getRandomBetween1and10());

// Something to take note of: see how the function you are
// returning has reference to the arguments passed to
// get, RandomGenerator? 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 context of the
// function (i.e., what `this`...