How can I read Javascript close syntax?

Based on some code in Doug Crockford's lecture, I 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

This is pretty cool, as it does an expensive installation only once, and each subsequent call is a cheap check.

However, I cannot decrypt the code that does this. In particular, I cannot understand why I need a "()" at the end of a function declaration.

Can someone explain how this syntax works?

+5
source share
4 answers

() . function() { } . () 1 ( ) isAlphaUser.

function() { ... }() , .

, :

  • , AlphaUsers .
  • , 1 . , AlphaUsers ( , ). , AlphaUsers (, , ).
  • isAlphaUser.
  • isAlphaUser , , , AlphaUsers, AlphaUsers ( ).

1 — . cwolves, , (), }, , , . function , , , , ( , ) inline. . .

+13

() . parens () , , , ().

+1

, , "()" .

self-invoking, , , .

, (), :

myfunc();   // call this func
+1

, isAlphasUser varaible.

, .

: - factory, .. .

To use any function (even one that returns a function), you must call it.

0
source

All Articles