Coding with JavaScript For Dummies
Book image
Explore Book Buy On Amazon

JavaScript has a data type called object. JavaScript objects encapsulate data and functionality in reusable components. You may find that creating an object is the next logical step in your coding journey.

JavaScript has two ways to create objects:

  • By writing an object literal

  • By using the object constructor method

Which one you choose depends on the circumstances. Here, you discover the pros and cons of each and when one is preferred over the other.

Defining objects with object literals

The object literal method of creating objects starts with a standard variable definition, using the var keyword, followed by the assignment operator:

var person =

In the right side of the statement, however, you’ll use curly braces with comma-separated name/value pairs:

var person = {eyes: 2, feet: 2, hands: 2, eyeColor: "blue"};

If you don’t know the properties that your object will have when you create it or if your program requires that additional properties be added a later time, you can create the object with few, or even no properties, and then add properties to it later:

var person = {};
person.eyes = 2; = "brown";

document.write and console.log both use this method of separating properties with a period, so it may look familiar to you. The dot between the object name and the property indicates that the property belongs to that object.

Another thing to notice about objects is that, like arrays, objects can contain multiple different data types as the values of properties.

The not-so-well-kept secret to really understanding JavaScript is in knowing that arrays and functions are types of objects and that the number, string, and Boolean primitive data types can also be used as objects. What this means is that they have all the properties of objects and can be assigned properties in the same way as objects.

Defining objects with an Object constructor

The second way to define an object is by using an Object constructor. This method declares the object using new Object and then populates it with properties. An example of using an Object constructor is shown here.

var person = new Object();
person.feet = 2; = "Sandy"; = "black";

The Object constructor method of creating objects can be used, but it’s generally regarded as the inferior way to create objects. The main reasons are

  • It requires more typing than the object literal method.

  • It doesn’t perform as well in web browsers

  • It’s more difficult to read than the object literal method.

About This Article

This article is from the book:

About the book authors:

Chris Minnick is an accomplished author, trainer, and web developer who has worked on web and mobile projects for both small and major businesses. Eva Holland is an experienced writer and trainer who has designed and taught online, in-person, and video courses. They are cofounders of WatzThis?

This article can be found in the category: