I’m working my way through the Eloquent JavaScript Book and in it there is the following code:
function createFunction(){
var local = 100;
return function(){return local;};
}
When I run this via the node console (run node from command prompt) by calling createFunction(), I get [Function] as a returned value. However, according to the book I should get 100.
So my two questions: Why is this? and Second, is running these little examples in the node console a bad idea for testing JS code?
You need to call the response of
createFunction().The first invocation (
()) callscreateFunction()and returns the inner function, which the second invocation executes and returns thelocalvariable which was closed over.Running small examples in a node console (or any other) is fine, so long as you know the environment, e.g. a browser’s console is generally
eval()‘d, which can create side effects, such as howdeletecan apparently delete variables, not just object properties.