This forum is now read-only. Please use our new forums! Go to forums

0 points
Submitted by Jack Cannon
almost 10 years

Object vs Array

Hello,

What’s the difference between an object and an array? For example, the following two pieces of code seem equivalent to me:

Array:

var Merica = [];
Merica[0] = "Red";
Merica[1] = "White";
Merica[2] = "Blue";

Object:

var Merica = {Color1: "Red", Color2: "White", Color3: "Blue"};

It seems like if I wanted to store a list of things in one place, I could use an array or an object. Which ones do you use in which situations? What’s the difference?

Thanks!

Answer 53a8252380ff3394b00075e6

2 votes

Permalink

Hi Jack, first of all they are both objects and so are functions, objects. Almost everything in JavaScript is an object.

Imagine you have two pocket folders with several slots each where you store your papers.

Each slot on the first pocket folder is labeled 1,2,3,4, etc

Each slot on the second pocket folder is labeled “Bills to pay”, “Gas receipts”, “Medical receipts”, etc.

These two pocket folders have different reasons to exist, right?

If you call home you would tell your brother/sister to “get the document of pocket number 3“.

Or, if on the other folder, “You will find the receipt on the pocket labeled “Medical receipts”.

The numeric folder is an array or you can also call it an “ordered list“ because it is numerically ordered. We know it is an array when its values are surrounded by [ ].

The labeled folder is what you call an object but its real name is “unordered list“ or “hash”. We know it is an unordered list if it has labels and it is surrounded by { }


What confuses people is that we address each location in arrays and hashes the same way: myPokectFolder[3] <– which means the value of the 4th slot since it starts counting from 0.

or myPokectFolder[“Gas receipts”] <– which means the value in the pocket labeled “Gas receipts”, no numeric order necessary.


Anyway, hope it helps. Let me know if you still have a question

points
Submitted by tony de araujo
almost 10 years

Answer 53a9037a282ae3ebe600194c

0 votes

Permalink

Thank you for the thorough reply! That definitely helps clarify things for me. So just to be clear, the difference is mainly a matter of indexing (numerical = array, string = object)?

Thanks again!!

points
Submitted by Jack Cannon
almost 10 years

1 comments

tony de araujo almost 10 years

Yes, the difference is how they are indexed. That different plays an important roll on which type to use for any given situation. Sometimes order is necessary, other times flexibility is what we need. Glad it helps.