1

I notice a difference when I declare a variable as an array or object and then add elements to it.

When I declare my variable as below:

var my_array = [];
my_array["a"] = 'first';
my_array["b"] = 'second';
console.log(my_array);

I get the following result:

[a: "first", b: "second"] 

However, when I do the following:

var my_array = {};
my_array["a"] = 'first';
my_array["b"] = 'second';
console.log(my_array);

This is the result I get:

Object {a: "first", b: "second"} 

What is really going on here?! Is one way standard, and the other not?! What are the downsides with compatibility?!

Thanks in advance.

P.S. I'm using Google Chrome.

ObiHill
  • 11,448
  • 20
  • 86
  • 135

2 Answers2

2

The first is an array and the secound is an object, which one to use depands on your goal, if you need arrays the array will be more usefull and effiecent than using an "array" object.

Further more an object can be used like this: myObject.a

While an array can be only used like this: myArray["a"]

Another diffrence is in the toString method. For an array it returns Banana,Orange,Apple,Mango (for example) and for an object it returns [object Object](for example).

For further reading: What is the difference between an array and an object?

Check if is array:

function isArray(obj) {
    return Object.prototype.toString.call(obj) === "[object Array]";
}
Community
  • 1
  • 1
Dan Barzilay
  • 4,974
  • 5
  • 27
  • 39
  • Thanks. I'm trying to find a way to differentiate the two in code, how do I do this? Can I just use toString and test which one returns a string as opposed to an object?! – ObiHill Nov 27 '12 at 12:22
0

They are two different objects. I use the second for JSON response, and the first for normal use in the code.

ilCrosta
  • 95
  • 1
  • 5