JavaScript Function Exercises

For introduction to JavaScript presentation.

by Matt Swensen

JavaScript

////////////////////////////////////////
// Excercise 1: First-class Functions //
////////////////////////////////////////

// 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 prod = Math.floor(a / b),
      mod = a % b;

  callback(prod, mod);

}

// Try it: invoke divide() with two integers and an
// anonymous function as parameters.






///////////////////////
// Utility functions //
///////////////////////

// Use this to print things to the HTML document.

function print() {
  var body = $('body');
  _.forEach(arguments, function(arg) {
    body.append($('<pre>').text(arg));
  });
}