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.
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.aWhile an array can be only used like this:
myArray["a"]Another diffrence is in the
toStringmethod. For an array it returnsBanana,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: