JavaScript object basics

Tags: 

What's an object?

An object is a collection of data about something. Here's an example:

var bestDog = { name: "Oscar", breed: "Black lab", weight: 85 };

The object bestDog has three properties. Each property has a key and a value. The first property has a key of name, and a value of "Oscar". The last property has a key of weight, and a value of 85.

Keys are usually strings, like name, breed, and address. Values can be all sorts of things: strings, numbers, objects, arrays, other things.

Suppose we had this code:

alert( bestDog.name );

Recall that alert shows a message on the screen. We would see:

Oscar

This...

alert( bestDog.weight );

...would show...

85

You can try it.

A property's value can be another object. Like this:

var author = { name: "Kieran", children: { Cullen: "male", Teagan: "female" } };

The first property, name, has a string ("Kieran") as a value. The second property has the key children. Its value is another object: { Cullen: "male", Teagan: "female" }.

How about this?

alert( author.children.Teagan );

It shows:

Female

Note that keys are case-sensitive in JavaScript. Teagan works; teagan does not.

A page using an object

OK, not a very good page, but it does something. Try it. You type in a name and address, and it will format a mailing label.

Here's the JS:

  1. $(document).ready(function(){
  2.   //Input data from user.
  3.   var lastNameInput = prompt("Last name?");
  4.   var firstNameInput = prompt("First name?");
  5.   var addressInput = prompt("Address?");
  6.   //Put into an object.
  7.   var person = {
  8.     lastName: lastNameInput,
  9.     firstName: firstNameInput,
  10.     address: addressInput
  11.   };
  12.   //Create the label.
  13.   $("#last-name").text(person.lastName);
  14.   $("#first-name").text(person.firstName);
  15.   $("#address").text(person.address);
  16. });

The prompt function asks the user to type in some data. Lines 7 to 11 create an object from that data. Lines 13 to 15 place the data into HTML elements that are formatted to look like a mailing label.

Summary

An object is a collection of data about something. Objects have properties of the form key: value. Keys are usually strings, but values can be different types of things, including other objects.