Introduction to Objects in JavaScript

by kirupa   |   27 November 2013

JavaScript is known as an Object Oriented Programming (OOP) language. You may have heard that before. Basically, all of this is just a fancy way of saying that everything you do will revolve around working with what are known as objects. Properly understanding objects and how to use them isn't something that can be rushed. This is a pretty big and important topic, and we'll take it slow and chew on everything in bite sized pieces!

In this tutorial, I'll provide an overview of what objects are and how to use them. By the end of this, not only will you learn how to work with objects in JavaScript, you will hopefully also gain an appreciation for the value they provide.

Onwards!

What are Objects?

The concept of objects in a programming language like JavaScript maps nicely to its real-world equivalents. In the real world, you are literally surrounded by objects. Your computer is an object. A book on a shelf is an object. A potato is (arguably) an object. Your alarm clock is an object. The autographed Cee Lo Green poster you got on Ebay is also an object! I could go on forever, but (for everyone's sake :P) I'm going to stop here.

Some objects like a paperweight don't do much:

 

paperweight

 

They just sit there. Other objects, like a television, go above and beyond the call of mere existence and do a lot of things:

a television

A typical television takes input, allows you to turn it on or off, change the channel, adjust the volume, and do all sorts of television-y things.

The thing to realize is that objects come in different shapes, sizes, and usefulness. Despite the variations, objects are all the same at a high-level. They are an abstraction. They provide an easy way for you to use them without having to worry about what goes on under the covers. Even the simplest objects hide a certain level of complexity that you simply don't have to worry about.

For example, it doesn't matter what goes on inside your TV, how the wires are connected, or what type of glue is used to hold everything together. Those are unnecessary details. All that you care about is that the TV does what it is told. When you want it to change the channel, the channel should change. When you adjust the volume, the volume should adjust. Everything else is just noise.

Basically, think of an object as a black box. There are some predefined / documented things it does. How it does them is something you can't easily see. How it does its magic is also something you don't really care about as long as it works. We'll change that notion later when we learn to actually create the insides of an object, but let's relish this simple and happy world for now.

Objects in JavaScript

Now that you got an overview of objects in the real world, let's leave that world behind. This simplified view of objects described in the previous section applies to the fun and exciting world of JavaScript as well. In JavaScript, everything you see and touch in code is an object. EVERYTHING. Every line of code you write will involve working with objects - even if you don't realize it.

Let's shine some more light on the various things you will be doing with objects...starting with the creation side of things!

Creating Objects

The first thing we'll look at is how to create objects. The way you create objects in JavaScript is by cloning them from other objects:

parent children relationship

Basically you have a parent object, and you create child objects from it. The parent is not anything special like it might be in other languages. It is just an object that can do all sorts of object-y things with.

You create objects using the very appropriately named Object.create function (aka a method) and passing in the name of the object you want to create your new object from. Let's assume the name of our parent object is going to be called theCircle.

Below is an example of what creating a new object called greenCircle based on the theCircle object looks like:

var greenCircle = Object.create(theCircle);

Last thing on this topic before we move on. There are many ways to create objects in JavaScript. The Object.create approach you've seen here is just one of them, and it is personally my favorite. Another popular approach is using the new keyword and a constructor function. I will touch upon that briefly much later. The last approach is one where objects just get created on the fly as needed. You'll see this one in a few sections.

Creating objects is only part of the fun. Changing things on the objects is funner-er. Let's look at that next.

Setting and Reading Properties

In the real world, objects often have a size, shape, color, smell, utility, and other characteristics. Objects in JavaScript are no different, for they too have certain characteristics and functions associated with them. In the JavaScript side of the world, these characteristics and functions are defined using something known as properties.

Here is an example of our theCircle object with some properties defined on it:

the circle object 

A property is nothing more than a name associated with a value. The properties defined on our theCircle object are color, size, outline, and bounce. Right now, no values have been defined, and a property is only as valuable as the value (ha!) it stores. Let's fix that.

Setting a property on an object is pretty simple, and just like everything in JavaScript, there are several ways to do this. One way involves specifying the property name on the object with a period between the object and the property name. Here is what setting the color property on our greenCircle object looks like:

var greenCircle = Object.create(theCircle);
greenCircle.color = "#669900";

Notice that I set the color property on our greenCircle object to a green value of #669900. Another way of setting the property is by using a bracket syntax. It's easier to show you first before explaining it, so here is an example of the same color property being set using this approach:

var greenCircle = Object.create(theCircle);
greenCircle["color"] = "#669900";

The end result is that the color property gets set on the greenCircle object. Whichever approach you use, you'll be just fine.

The thing to be aware of is that there are no real restrictions on what you can specify as a value for a property. A property value can be any number, function, or another object itself. This unrestrictive and freewheeling nature of JavaScript is either a good thing or a bad thing depending on who you ask.

To read a property's value, simply access it via the same dot or bracket notation you used for actually setting the property value:

var greenCircle = Object.create(theCircle);
greenCircle.color = "#669900";

// display the color
alert(greenCircle.color);

// alert(greenCircle["color"]);

This is all pretty straightforward, as you can see. In fact, everything you've seen so far from creating an object to setting properties shouldn't be too complicated. Before we wrap things up with our theCircle object, let's look at just one more case!

Creating Many Objects

Objects not only abstract details, they are also pretty self-contained. You can have many objects of the same type in close proximity with each other, and they will all behave and play nicely. For example, let's say you have some code that looks as follows:

var greenCircle = Object.create(theCircle);
greenCircle.color = "#669900";
greenCircle.size = 150;

var pinkCircle = Object.create(theCircle);
pinkCircle.color = "#FF0066";
pinkCircle.size = 100;

var yellowCircle = Object.create(theCircle);
yellowCircle.color = "#FFCC00";
yellowCircle.size = 75;

In this code, we are creating three objects based on the theCircle object with each one having a different color and size. If you had to visualize the end result, it would look as follows:

three!!!

This ability for objects to be self-contained mini-applications of their own is something you will rely on as you get deeper into building larger things.

Putting it All Together: Meet the String

As you can imagine, the theCircle object is not something that is built-in to JavaScript. While looking at a made-up example is good for helping you understand the concepts, let's close things out by looking at something real that actually exists! JavaScript comes with a handful of built-in types that represent everything from text to numbers to collections of data to just plain objects. Let's review everything we've learned by looking at how to work with the very text-friendly String object.

Let's say you have some code that looks as follows:

var someText = "hello, world!";
alert(someText);

What you have is a variable called someText, and its value is set to hello, world! If you run this code, you will see hello, world! displayed in a dialog:

hello world displayed in a dialog

If this all looks a bit familiar, it should! This is just a slight variation to what you saw in the variables tutorial earlier.

Now, here is the thing. The someText variable isn't an object in its current state. This makes up a handful of data types you will find that are primitive (aka in their most simple, non-object form) in their natural environment. The moment you try to access properties on them, these data types suddenly become full blown objects. The end result is the same as working with any normal object, so I won't make fun of this behavior too much.

Wait...say what?

What this means is pretty simple and significant (aka simplificant). Like I mentioned earlier, the Object.create approach isn't the only way to create a new object. Yes, major spoiler alert. To give you a preview of something you'll be learning later, a String object can be created in the following ways - all of which result in sort of the same thing:

var someText;

someText = "hello, world!";
someText = new String("hello, world!"); // phew!
someText = String("hello, world!");

The end result is a String object in the second and third examples. The first example results in a string primitive that gets converted into a String object the moment you try to access properties on it. As someone British (with a hint of Canadiana) might say, "Sneaky little bugger, eh?"

Don't worry if all this doesn't make sense yet. Just know that you can access the String properties on all three of these approaches. The subtle (and not-so-subtle) differences among these three is something I will elaborate on in the future.

The String object contains a boatload of properties and methods. Some common ones include:

We'll look at the String object in greater detail later, but for now let's focus on using a handful of properties so that we get a better feel for working with a real (and very complex) object without worrying about the behind the scenes details.

Meet the length Property

A great property to start our exploration off with is the length property. What the length property does is pretty simple. It tells you how many characters make up your string.

To get the length of our someText object, all you have to do is the following:

var someText = "hello, world!";
alert(someText.length);

When you run this script, notice that you will see the number 13 displayed:

the length of our text

Because I've repeated the primitive-to-object conversion that happens when you call String-like properties on our text, there should be no surprises here. The length property works as advertised.

Let's do one more thing before we call it a night...or day depending on when you are reading this!

Calling Functions (ahem...Methods)

Like I mentioned earlier, the property values for an object can be anything...such as a function. An example of a property whose value is a function is the String object's toUpperCase property. When you call toUpperCase on some text, that text becomes fully capitalized:

var someText = "hello, world!";
alert(someText.toUpperCase());

Notice how I am calling toUpperCase. Because it is a function that takes no arguments, I just call it using the empty parenthesis following it. Now, here is a terminology change that you need to be aware of. Because toUpperCase is a function that is used as a property inside an object, it now has a new name. That new name is method. Many people use the function and method terminology interchangeably, so just be aware of that. They both mean the same thing. It is just that one very obviously lives off an object and the other one doesn't.

Since we are already here, if you have a method that takes arguments, simply specify the arguments for them like you would for any plain ol' function. A great example of a method that takes an argument is the String object's charAt! The charAt method takes a number as an argument, and that number corresponds to the index position of a character in your text.

Below is a diagram showing the index positions of all the characters in our hello, world! text:

 

text position

 

Here is how you would use the charAt method on someText to figure out the character in the tenth position:

var someText = "hello, world!";
alert(someText.charAt(9));

Because the counting of character positions starts at 0, the tenth position is actually represented by a 9. As you can see from the earlier diagram, what you should see is the r character getting returned:

the r dialog

As an aside, something you will come to learn is that most indexing starts at 0. This means that you need to mentally shift how you think about counting and pinpointing things by 1. This is a quirk that you will see throughout JavaScript and many other languages. Anyway, I digress.

At this point, you just got a whirlwind tour of how to work with objects by using the String as a guinea pig for our (very humane!) experiments. Let's do the boring closing remarks next.

Conclusion

Objects are everywhere in JavaScript. As you've seen several times already, objects provide a way of separating the complexity that goes on behind the scenes from what you are actually wanting to do. The first part of this tutorial was just setting the stage and introducing the cast so that you are familiar with what you are dealing with.

We have only scratched the surface on what is possible to do with objects. Even though we only looked at using predefined objects in this tutorial, there are a lot of subtleties that I have glossed over. These subtleties and more will be gradually covered in later tutorials that take bigger and bigger bites of this very unhealthy (but very tasty) JavaScript flavored dessert. In fact, when you are ready, let's go on to the Deeper Look at Objects in JavaScript tutorial next.

Getting Help

If you have questions, need some assistance on this topic, or just want to chat - post in the comments below or drop by our friendly forums (where you have a lot more formatting options) and post your question. There are a lot of knowledgeable and witty people who would be happy to help you out

Share

Did you enjoy reading this and found it useful? If so, please share it with your friends:

If you didn't like it, I always like to hear how I can do better next time. Please feel free to contact me directly via e-mail, facebook, or twitter.

Brought to you by...

Kirupa Chinnathambi
I like to talk a lot - A WHOLE LOT. When I'm not talking, I've been known to write the occasional English word. You can learn more about me by going here.

Add Your Comment (or post on the Forums)

blog comments powered by Disqus

Awesome and high-performance web hosting!
BACK TO TOP
new books - yay!!!