How to Create a Basic Object in JavaScript for HTML5 and CSS3 Programming - dummies

How to Create a Basic Object in JavaScript for HTML5 and CSS3 Programming

By Andy Harris

JavaScript makes it trivially easy to build an object for HTML5 and CSS3 programming. Because a variable can contain any value, you can simply start treating a variable like an object and it becomes one.


Take a look at the following code:

 //from basicObject.html //create the critter var critter = new Object(); //add some properties = "Milo"; critter.age = 5; //view property values alert("the critter's name is " +;

The way it works is not difficult to follow:

  1. Create a new Object.

    JavaScript has a built-in object called Object. Make a variable with the new Object() syntax, and you’ll build yourself a shiny, new standard object.

  2. Add properties to the object.

    A property is a subvariable. It’s nothing more than a variable attached to a specific object. When you assign a value to, for example, you’re specifying that critter has a property called name and you’re also giving it a starting value.

  3. An object can have any number of properties.

    Just keep adding properties. This allows you to group a number of variables into one larger object.

  4. Each property can contain any type of data.

    Unlike arrays where it’s common for all the elements to contain exactly the same type of data, each property can have a different type.

  5. Use the dot syntax to view or change a property.

    If the critter object has a name property, you can use as a variable. Like other variables, you can change the value by assigning a new value to or you can read the content of the property.

If you’re used to a stricter object-oriented language, such as Java, you’ll find JavaScript’s easy-going attitude quite strange and maybe a bit sloppy. Other languages do have a lot more rules about how objects are made and used, but JavaScript’s approach has its charms. Don’t get too tied up in the differences. The way JavaScript handles objects is powerful and refreshing.