Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects Review Object Basics

Scott Wells
Scott Wells
8,715 Points

Best practices for objects and arrays...

I just learned about objects, and they are obviously even more versatile than arrays. In what instance is an object more preferable to an array? I can think of individual instances off the top of my head, but I am wondering if there are certain types of data or things in a JavaScript program that are regularly one or the other? Thanks

JavaScript is an object-oriented language. When it comes down to "objects or arrays"? It seems rather confusing, as both group together huge amounts of data. However, objects are commonly used for grouping different instances of the same thing.

For example, imagine you wanted to create a page that showed all the different types of car models. You can use an array to do this, but it would be very complicated and not so efficient. Using an object literal means you can describe exactly what you want about the car, such as the: model; color; make; engine and so on.

As you will further progress in JavaScript, you will begin to realize that Objects are almost everywhere, and are commonly used with functions to create "multiple instances" of data. So for example, using the same function to talk about a different car with different values for the variables you created inside the object.

To summarise:

1) Arrays can be used for grouping together related content such as a shopping list 2) Objects are also used for grouping together related things, however, it is often used for more complex data where you want to create multiple 'instances' or multiple types of data for the same variable with the use of a function

1 Answer

Steven Parker
Steven Parker
231,275 Points

Arrays actually are objects with a few unique qualities: all the keys are sequentially-assigned integers, they have a "length" property, plus a number of useful methods. For more details see this MDN page on Array.

Arrays are a good choice where you want to store a list of similar items, which may themselves be complex objects. Objects are good for collections of data that are not similar except by association.