The next example shows a variation of the functional scoping code. The createFunction definition creates a message variable and a displayMsg nested function that writes the message value to the console. Instead of invoking displayMsg within the createFunction function, this new function returns the displayMsg function object to the calling code. When code invokes createFunction, the calling code gets a reference to the displayMsg function, but doesn't invoke displayMsg.
The following code invokes createFunction and saves the reference to the returned function to the newFunc variable, then invokes the function returned by createFunction:
var newFunc = createFunction(); newFunc();
Not at all! This example shows closure at work. When createFunction defined the displayMsg function, the nested function closed around the variables in scope, retaining a reference to the message variable as long as the nested function is in scope. When the displayMsg function was invoked through the newFunc variable, the message was still in scope and retained its original string value. That’s the power of closures.