Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do returning curly braces mean in javascript (ex. return { init : init} ) [duplicate]

Tags:

javascript

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.

like image 937
Alex Avatar asked Dec 05 '22 10:12

Alex


1 Answers

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 ().

like image 144
Justin L. Avatar answered Mar 01 '23 14:03

Justin L.