Search results

JavaScript: Objects

It can be tedious to define separate variables when you have a collection of related information. Instead of defining each variable separately, you can create an object and list the variables as properties of the object. This makes it easier to manipulate all the variables. (Note that variables that are part of an object are called "properties" instead of "variables").

Quick Review of Objects

As a review, remember that arrays are objects. As an object, you can apply methods to them. For example:

//declare an array with some positions
var sampleArray [5,10,15,20,25];
//determine number of positions in
//the array using the .length method
console.log ( sampleArray.length );

The result is 5. There are 5 positions in the array.

Here's how you might use a method on a date object:

// define a new date object
var lastDay = new Date();
// find day of week using the .getDay method
console.log( lastDay.getDay() );

The result is the current day, which in this case is 1, or Monday.

Creating New Objects

You can create a new object that isn't an already an array or date object. To create a new object, define a new variable and assign it as a new Object();.

var team = new Object();

Once you have defined the new object, you can set up the various properties of the object. You list these properties by adding a dot and then the property name.

 //create a new object
var team = new Object();
//define the object's properties
team.size = 5;
team.name = "Panthers";
team.fouls = 7;
team.rating = "AAAA";

It's convenient to list each of these highly-related variables as properties of an object, rather than listing them out as separate variables.

You can use a shorthand syntax for creating an object and listing its properties. Rather than listing properties separately on their own lines, you can group them inside curly braces, separated by commas:

 var team = {size:5, name:"Panthers", fouls:7; rating:"AAAA"};

Whenever you need to call any of the variables, you list the object name followed by .property, like this:

console.log(team.fouls);

The result would be 7.

"This" Placeholder

In a JavaScript statement, sometimes you need a general placeholder that fits numerous variables. You can use this for exactly this purpose.

Here's an example of how you might integrate this.

 //create a couple of objects
var team1 = { size:5, name:"Panthers", fouls:7;
rating:"AAAA" };
var team2 = { size:5, name:"Lions", fouls:15;
rating:"AA" };</p>
<p>//create a function with "this" as placeholder
function teamProfile() {
console.log(this.name + "has a this.rating rating.");
}</p>
<p>//call the same function with different variables
team1.logDetails = teamProfile;
team2.logDetails = teamProfile;

This will return "Panthers has a AAAA rating" as well as "Lions has a AA rating."

Both team1 and team2 refer to the same function, teamProfile. When the function runs, because it uses this instead of something more specific, team1 and team2 will pass into this appropriately.

Properties and Methods

Objects can have both properties and methods. A property holds data about the object, whereas a method performs some action on the object. Both properties and methods are accessed through the dot operator that follows the object's name.

Here's an example:

var numberOfCharacters = message.length;

This variable will return the length of the message object. In this case, length tells us a property of the object.

A method will perform some action usually with the object's properties.

Data Types

Objects can have different data types.

JavaScript has some built-in objects, including the following:

  • Array
  • Date
  • Number
  • String

Arrays

Arrays are a data type that holds multiple values.

You create a new array data type with the following constructor:

var myArray = new Array();

This creates a new array and stores several values in it:

var gears = new Array(1, 2, 3);

There's also what's known as "literal notation" that involves brackets instead:

var myArray = [];

var gears = [ 1, 2, 3 ];

Each position in the array's values is called "index notation." The index refers to the position of the value in the array. It starts at 0 and increments from there.

There are a handful of useful methods to use with arrays:

  • concat (array1, array2): joins multiple arrays
  • join (separator): converts the array into a string
  • pop: removes the last array element
  • push (element): adds a new element to the array
  • reverse: reverses the order of the array's elements
  • sort: sorts the elements of the array into alphabetical order

Date Object

The Date object is another built-in data type in JavaScript. The new Date() constructor is used to create a new date object like this:

var date = new Date(); 

You can also create a date object by passing it some date information like this:

var date2 = new Date(2010, 0, 1);

The following are some methods for working with the Date object.

  • getFullYear()
  • getmonth()
  • getDate()
  • getDay()
  • toDateString()
  • setDate(dayOfMonth)
  • setMonth(monthNumber)
  • setFullYear(yearNumber)

Here are some methods related to time:

  • getHours()
  • getMinutes()
  • getSeconds()
  • getMilliseconds()
  • setHours(newHour)
  • secSeconds
  • setMilliseconds()

I'm not going to go into more detail, but you can work with the Number and the String object data types in depth as well.

Creating custom objects

You can create a new object in a couple of ways. This way would create a new object and set it as a variable called coordinates:

var coordinates = new Object();

There's another method that uses something called "literal notation" to accomplish the same thing:

var coordinates = {};

Recall that you can create an array object using the "array literal" shorthand, which involves using brackets. With new objects, you use curly braces instead.

Adding Properties to a New Object

Here's how you add properties to the new object:

var coordinates = {};
coordinates.x = 0;
coordinates.y = 0;

You could also create the new object and add its properties in one step:

var coordinates = {
    x : 0,
    y : 0
};

The x and y are property definitions for the coordinates object.

After you have set up the object, you can use it just like any other object:

var text = "X is " + coordinates.x + " and Y is " + coordinates.y;
alert(text);

Define a Method to Use with a New Object

You can also define a method for a new object. You do this in almost the same way that you list a property for the object, except that you write it as a function:

var coordinates = {
    x : 0,
    y : 0,
    sayCoordinates : function() {
        var text = "X is " + this.x + " and Y is " + this.y;
        alert(text);
    }
};

You'll notice that we're using "this" in the function that is written as a method for the coordinates object. The "this" term means "this object" and refers to the coordinates object. Because this function appears within the coordinates object, the "this" refers to the coordinates object. "This" means "this object."

Passing Objects as Arguments in a Function

You can even pass objects as arguments in a function. For example, suppose you have this function:

var point = getCurrentPoint();

You can actually pass the function as an argument, like this:

function drawPoint(point) {
    // do something with point.x
    // do something with point.y
}</p>
<p>var point = getCurrentPoint(); // get coordinates
drawPoint(point); // draw the dot on the screen</p>
<p>alert(point.x);
alert(point.y);

About Tom Johnson

Tom Johnson

I'm an API technical writer based in the Seattle area. On this blog, I write about topics related to technical writing and communication — such as software documentation, API documentation, AI, information architecture, content strategy, writing processes, plain language, tech comm careers, and more. Check out my API documentation course if you're looking for more info about documenting APIs. Or see my posts on AI and AI course section for more on the latest in AI and tech comm.

If you're a technical writer and want to keep on top of the latest trends in the tech comm, be sure to subscribe to email updates below. You can also learn more about me or contact me. Finally, note that the opinions I express on my blog are my own points of view, not that of my employer.