Skip to content Skip to sidebar Skip to footer

What Do Returning Curly Braces Mean In Javascript (ex. Return { Init : Init} )

I'm looking over this code: $(function(){ var $sidescroll = (function() { init = function() { //STUFF }; return { init : init }; //What d

Solution 1:

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

Solution 2:

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;

Post a Comment for "What Do Returning Curly Braces Mean In Javascript (ex. Return { Init : Init} )"