2

I'm doing a tuts tutorial on intel xdk and parse and one of the source files has this syntax I've never seen anywhere. The file itself opens with a function that not only has no name, but is declared inside regular parentheses. Can someone explain and/or link to some online resource that explains this?

(function (credentials) {

    var exports = {};
    var baseUrl = 'https://api.parse.com/1/classes/article/';

    exports.articles = function (params) {
    params = params || {};
    var artID = '';
    if (params.ID) {
        artID = params.ID;
    }
    var url = baseUrl + artID;
    return $.ajax({
        url: url,
        headers: {
        'X-Parse-Application-Id' : credentials.apiKey,
        'X-Parse-REST-API-Key' : credentials.apiSecret
        }
    });
    };


    return exports;
})
Spilot
  • 1,495
  • 8
  • 29
  • 55
  • 4
    I think it's supposed to have a `()` on the end because then it would be [an IIFE](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression). – Mike Cluck Feb 03 '16 at 01:10
  • In this [article](http://javascriptissexy.com/understand-javascript-closures-with-ease/) you find more information and other ways to use this syntax – dexhering Feb 03 '16 at 01:14
  • Right now it's just a function inside parentheses, that can't be called, and makes little sense. As noted by Mike, you're probably missing a pair of parentheses at the end. – adeneo Feb 03 '16 at 01:15
  • I see..I copied this code in its entirety from the tutorial documentation. I didn't write it myself. This is what was provided for me to work with. So did the original author do something wrong here? – Spilot Feb 03 '16 at 01:31

1 Answers1

4

Your code snippet as many pointed out, is most likely missing a pair of () at the end. With the (), it becomes a IIFE, this Wikipedia article pointed by Mike explains fairly clearly.

In brief, an immediately-invoked function expression is executed once your program encounters it. Consider the simple case below:

//Your awesome js
console.log(b); // undefined
(function() {
  b = "cat";
})();
console.log(b); // cat. Since in the above IIFE, we defined a global variable b.

You can also pass parameters into the IIFE like this:

(function(input) {
  console.log(input); // 5
})(5);

Your code above creates an "export" object and returns it. If you read the "Establishing private variables and accessors" section in the Wiki, you'll see how that is similarly used to nicely create "private" variables.

Shawn Xu
  • 163
  • 4