Jump to content

JavaScript/Closures/Exercises

From Wikibooks, open books for an open world

Topic: Closure



1. Write a script that creates a parameterizable function decoratorFactory. It accepts a string that 'decorates' logging information with the given parameter. E.g.: const tiny = decoratorFactory("Log message from subroutine 'someTinyAction': "); alert(tiny("Division by zero."));. The script shall internally use a closure.

Click to see solution
"use strict";

function decoratorFactory(someText) {
  // 'someText' is known in 'decoratorFunction' as well as in 'logFunction'
  const logFunction = function (message) {
    // use 'someText' from the outer lexical environment and the function's parameter 'message'
    return(someText + ": " + message) // maybe: plus timestamp, ...
  }
  return logFunction;
}

const computeMsg = decoratorFactory("Log message from subroutine 'computeAverage'");
alert(computeMsg("Division by zero."));

const main = decoratorFactory("*** Log message from 'main'");
alert(main("No database connection."));

alert(main("Unknown system error."));