JavaScript Tip: Creating an Object

As with arrays, there are a couple of ways to create objects, and, just like arrays, one is preferred over the other. So even though you can do this:

You can also use object literal notation:

It’s safer to use the object literal notation {} as it’s unable to be overwritten. The object literal represents a new, empty object.

Whereas in an array, values are simply added and accessed by index, objects use a key/value pair system. These two distinct ways of storing values make it fairly simple when choosing between arrays or objects for your data storage and retrieval
needs.

For example:

Note how the lotteryNumbers array lends itself well to storing the sequence of lottery numbers, while the profile object is perfect for storing the key/value pairs of a person’s (Hugo’s) profile.

Leave a Reply

Your email address will not be published. Required fields are marked *