1

Can someone please explain how the following javascript code:

var temp = {};

temp[0] = "a"
temp[1] = "b"
temp[2] = "c"

if different from an array like

var temp = new Array();

or

var temp = []

I don't really understand if the first example "temp = {}" can be considered an array or is it some kind of object?

There is no spoon
  • 1,747
  • 2
  • 21
  • 49
  • js object is object array is also object – Arun Killu Feb 28 '14 at 09:16
  • 1
    Have you searched the internet? I found this in like 1 minute, http://www.youtube.com/watch?v=LYalKR2W-DU, http://eloquentjavascript.net/chapter4.html, http://msdn.microsoft.com/en-us/library/89t1khd2(v=vs.94).aspx, – elclanrs Feb 28 '14 at 09:16
  • Presumably (?) the temp object is still an Object, not an Array, so it will NOT have a length property, nor the various Array methods – Max Feb 28 '14 at 09:20

2 Answers2

1

var temp = {}; is an object with representation like Object {0: "a", 1: "b", 2: "c"} var temp = [] is an array with representation like ["a", "b", "c"]

while var temp = new Array(); is again the same thing like temp = []

More detailed information here What’s the difference between "Array()" and "[]" while declaring a JavaScript array?

Community
  • 1
  • 1
Durgesh Chaudhary
  • 1,038
  • 2
  • 12
  • 28
1

The first one creates an object:

var temp = {};

The second one creates an array:

var temp = new Array();

In any case you can access them as they are an array:

var temp = {};
temp[1]="in object";
console.log(temp[1]);

same as

var temp = []
temp[1]="in array";
console.log(temp[1]);