1

Im coding a BackboneJS example app with the following syntax

<script type="text/javascript">
    var object = [];

    _.extend(object, Backbone.Events);
     object.on("alert", function(msg)
    {
       console.log("Your name is: "+msg);
     });

    object.trigger("alert","Sarah");
</script>

I noticed that the app works if the variable is defined like this

var object = {}

is there any difference between the two?

oh I found this example http://eloquentjavascript.net/chapter4.html

{} is used to pass JSON like this

var cat = {colour: "grey", name: "Spot", size: 46};

[] is just an array

var cat = ["color one", "color two", "color three"];

thanks

Gabriel ThaKid
  • 857
  • 3
  • 9
  • 19
  • Well {} isn't strictly used for JSON. It's used to instantiate javascript objects in general but I understand the confusion. – spassvogel Feb 20 '14 at 16:00
  • @NiettheDarkAbsol: Not exactly everything. Both are objects (though one is a special `Array` object). – Bergi Feb 20 '14 at 16:02
  • so what exactly would be the difference between var object = {} and var object = null aren't they both empty variables? since a variable is an object too, im confused =/ – Gabriel ThaKid Feb 20 '14 at 16:04

2 Answers2

4

An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ([]).

An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}).

CD..
  • 72,281
  • 25
  • 154
  • 163
3

In short: [] is an array and {} is an object.

[] is shorthand for new Array()
{} is shorthand for new Object()

Basically, an Array is also an Object, but with added functionality. It is however, discouraged to use the Array as a hashmap (so, using strings as accessors).

Also, in your code the Array seems to be extended to have some sort of event mechanism. Personally I would use an object rather than an array but I guess there are reasons for this?

var object = [];
_.extend(object, Backbone.Events);
 object.on("alert", function(msg)
{
   console.log("Your name is: "+msg);
 });

object.trigger("alert","Sarah");
spassvogel
  • 3,479
  • 2
  • 18
  • 23