There is no spoon
There is no spoon

Reputation: 1796

Is this javascript declaration an array or some kind of object

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?

Upvotes: 1

Views: 56

Answers (2)

piacente.cristian
piacente.cristian

Reputation: 777

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]);

Upvotes: 1

Durgesh Chaudhary
Durgesh Chaudhary

Reputation: 1077

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?

Upvotes: 1

Related Questions