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

3
  • Well {} isn't strictly used for JSON. It's used to instantiate javascript objects in general but I understand the confusion. Commented Feb 20, 2014 at 16:00
  • @NiettheDarkAbsol: Not exactly everything. Both are objects (though one is a special Array object). Commented Feb 20, 2014 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 =/ Commented Feb 20, 2014 at 16:04

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

all answers were good, but this one is the best
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");

1 Comment

thanks, there is actually no reason for this, the original code is coded with "{}" too

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.