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.

2
  • Difference located in toString method. That's it. Commented Nov 27, 2012 at 11:17
  • try console.log(my_array.length); on both ... Commented Nov 27, 2012 at 11:20

2 Answers 2

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]";
}
Sign up to request clarification or add additional context in comments.

1 Comment

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?!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.