Skip to content

Instantly share code, notes, and snippets.

@talentedmrjones
Last active August 29, 2015 13:57
Show Gist options
  • Save talentedmrjones/9745311 to your computer and use it in GitHub Desktop.
Save talentedmrjones/9745311 to your computer and use it in GitHub Desktop.
arguments.callee is not the "name"
(function (n) { // function has no name, is therefore "anonymous"
var i=n*2;
if (i > 4) {
return undefinedFunc(); // causes a "ReferenceError: undefinedFunc is not defined at Object.<anonymous>"
} else {
arguments.callee(i); // recurses, adding the anonymous function to the call stack
}
})(1);
(function factor (n) { // function has a name, is not "anonymous"
var i=n*2;
if (i > 4) {
return undefinedFunc(); // causes a "ReferenceError: undefinedFunc is not defined at factor"
} else {
factor(i); // recurses, adding named function to the call stack
}
})(1);
@talentedmrjones
Copy link
Author

@mrgenixus Ultimately I was trying to show my students that a "self-executing anonymous function" is technically impossible in ES5 strict mode. I agree that the example here is not terrible useful and the function did not need to be anonymous; it was just a quick way to generate a stack trace showing named versus anonymous.

When actively coding I tend to be a pragmatist as well, but when teaching I'm very technical, pushing my students (and myself) to understand the language as deeply as possible, and as a result I often argue philosophically rather than pragmatically.

So yes, the point here was strictly semantic and technical. The value is in understanding scope: where in the code is any given reference available? An "anonymous" function as shown here is only available through the reference arguments.callee. A named function is available through the name, the name "factor" here is only available within the function scope, not outside of it. I think these points are important because I find that for most people learning javascript, their biggest hangup is usually related to scoping.

And yes, the side effect of having "factor" show up in the stack trace is definitely helpful when debugging nested callbacks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment