4

I'm looking over this code:

$(function(){
    var $sidescroll = (function() {
        init = function() {
            //STUFF
        };
        return { init : init };    //What does this do?
    })();
    $sidescroll.init();
});

What does the return statement mean? I haven't seen curly braces in a return statement before, and am not even sure what 'init : init' does.

Alex
  • 852
  • 1
  • 10
  • 21

2 Answers2

14

Curly braces mean two things in javascript:

  1. blocks
  2. object literals

You've probably seen the second -- also known in other languages as "dictionaries", key-value pairs, associative arrays, etc:

myDict = { a: "apple", b: "banana" };

When we say

return { a: "apple" };

it is the same as saying

myDict = { a: "apple" };
return myDict;

The "confusing" thing in this case is that (1) the key and the value are identical/have the same character representation, and (2) the value is not a normal string or variable but, a function. That is, accessing the key "init" of your object/dictionary will give you a function that you can call with ().

Justin L.
  • 13,510
  • 5
  • 48
  • 83
5

It returns a new Object instance with the init field set to the value of the init variable. This is called an "Object literal"

I.e.

return { init : init }; 

is the same as

var o = new Object();
o.init = init;
return o;
Stefan Haustein
  • 18,427
  • 3
  • 36
  • 51
  • ... except much less verbose :-) – John Dvorak Jul 07 '13 at 21:25
  • 1
    Two upvotes for answering a trivial JS question. Interesting question about floating point precision gets blocked. This is stackoverflow... :-/ http://stackoverflow.com/questions/17509179/how-to-improve-the-precision-of-the-result-due-to-the-lack-of-precision-in-c-d – Stefan Haustein Jul 07 '13 at 21:30