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;
})
asked Feb 3, 2016 at 1:07
4
  • 4
    I think it's supposed to have a () on the end because then it would be an IIFE. Commented Feb 3, 2016 at 1:10
  • In this article you find more information and other ways to use this syntax Commented Feb 3, 2016 at 1: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. Commented Feb 3, 2016 at 1: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? Commented Feb 3, 2016 at 1:31

1 Answer 1

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.

answered Feb 3, 2016 at 1:43
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.