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.





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





// 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
// 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 context of the
// function (i.e., what `this` refers to) when you invoke it.
// Consider the simple function below:

function logMe() {
    print(this.constructor.name + ': ' + this);
}

// The result of logMe() will be different depending on which
// context it is...