Learning web technologies one class at a time

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:

JavaScript

1

varmyObject=newObject();

You can also use object literal notation:

JavaScript

1

varmyObject={};

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:

JavaScript

1

2

3

4

5

6

7

8

9

10

varlotteryNumbers,profile;

lotteryNumbers=[4,8,15,16,23,42];

profile={

firstName:"Hugo",

lastName:"Reyes",

flight:"Oceanic 815",

car:"Camaro"

};

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.