Based on some code in a lecture by Doug Crockford, I’ve created this.
var isAlphaUser = (function() {
alert("Forming Alpha User List");
let AlphaUsers = {
1234: true,
5678: true
};
return function(id){
alert("Checking Alpha Users:",id);
return AlphaUsers[id];};
}());
alert("starting");
alert(isAlphaUser(1234));
alert(isAlphaUser(5678));
alert(isAlphaUser(3456));
which gives me this:
Forming Alpha User List
starting
Checking Alpha Users: 1234
true
Checking Alpha Users: 5678
true
Checking Alpha Users: 3456
undefined
Which is quite cool, as it does the expensive setup once only, and every further call is a cheap check.
However, I can’t decipher the code that does this. Specifically, I can’t understand why I need the “()” at the end of the function declaration.
Can somebody explain how this syntax is working?
()calls a function.function() { }defines a function. Appending()right after immediately calls it1, and the result (also an anonymous function) is assigned toisAlphaUser.The
function() { ... }()pattern is frequently used to isolate variables to an inner scope, so those variables don’t become part of the global scope.In this case, this is what happens:
AlphaUsersinside that scope.AlphaUsersvariable becomes bound (in other words, available). This function checks if the parameter passed in is contained inAlphaUsers(actually, it returns the item at that index, which is just a boolean).isAlphaUser.isAlphaUseris now a function, it can be called to see if the parameter is contained in theAlphaUsersvariable, but no direct access toAlphaUsersis available in the global scope (it become a sort of private variable).1 — Note: As cwolves mentioned in the comments, beware that while
()appended directly after the}works in this case, it is only because in this case the function definition is a function expression. Iffunctionis the first word on the line, the line becomes a function declaration, and that is all that line can do, the function is not anonymous (it will require a name, otherwise it’s a syntax error) and cannot be called immediately inline. See Function Declarations vs. Function Expressions for more info.