Of Pizza, Types, Primitives, and Objects

by kirupa   |   19 March 2014

It's time to get serious. Srsly! In the past few tutorials, we've been working with all kinds of values. You've worked with strings, numbers, booleans (aka true and false), functions, and various other built-in things that are part of the JavaScript language.

Below are some examples to jog your memory:

var someText = "hello, world!";
var count = 50;
var isActive = true; 

Unlike other languages, JavaScript makes it really easy to specify and use these built-in things. You don't even have to think about or plan ahead to use any of them. Despite how simple using these different kinds of built-in things is, there is a lot of detail that is hidden from you. Knowing these details is important because it will not only help you make sense your code more easily, it may even help you to more quickly pinpoint what is going wrong when things aren't working the way they should.

Now, as you can probably guess, "built-in-things" isn't the proper way to describe the variety of values that you can use in JavaScript. There is a more formal name for the variety of values you can use in your code, and that name is types. In this tutorial, you are going to get a gentle introduction to what they are.

Onwards!

Let's First Talk About Pizza

No, I haven't completely lost it. Since I am always eating something (or thinking about eating something), I am going to try to explain the mysterious world of types by first explaining the much simpler world of pizza.

In case you haven't had pizza in a while, this is what a typical pizza looks like:

it's pizza time!

A pizza doesn't just magically appear looking like this. It is made up of other ingredients - some simple and some not-so-simple:

 

the ingredients

 

The simple ingredients are easy to spot. These would be your mushrooms and jalapenos. The reason these are simple is because you can't break these ingredients apart any further:

 

simple enuf

 

They aren't prepared. They aren't made up of other simple ingredients. Just like the dude, they abide.

The not-so-simple, complex ingredients would be your cheese, sauce, crust, and the pepperoni. These are more complex for all the reasons the simples one are...um...simple. These complex ingredients are made up of other ingredients:

these are your complex ingredients

Unfortunately for all of us, there is no one ingredient called cheese or pepperoni out there. You need to combine and prepare and add some more ingredients to make up some of the complex ingredients you see here. There is a subtle wrinkle to call out about complex ingredients. Their composition isn't limited to just simple ingredients. Complex ingredients can themselves be made up of other complex ingredients. How scandalous?!!

From Pizza to JavaScript!

While this may be hard to believe, everything you learned about pizzas in the previous section was there for a purpose. The description of the simple and complex ingredients very neatly applies to types and JavaScript. Each individual ingredient could be considered a counterpart to a type that you can use:

 

the various types

 

Just like the cheese, sauce, pepperoni, mushrooms, and bacon in our version of a pizza, the basic types in JavaScript are string, number, boolean, null, undefined, and Object. Some of these types may be very familiar to you already, and some of them may not be. While we will look at all of these types in much greater detail in future tutorials, the following table provides a very brief summary of what they do:

Type What it does
string the basic structure for working with text
number as you can guess, it allows you to work with numbers
boolean comes alive when you are using true and false
null represents the digital equivalent of nothing...or moo :P
undefined while sorta similar to null, this is returned when a value should exist but doesn't...like when you declare a variable but don't assign anything to it
Array helps store, retrieve, and manipulate a collection of data
Object acts a shell for other types including other objects

Now, while each of the types is pretty unique in what it does. There is a simple grouping they fall under. Just like with your pizza's simple and complex ingredients, your types can be simple or complex as well. Except, in JavaScript terminology involving types, simple and complex are more formally known as primitive and object respectively. Another way of saying this is that your types in JavaScript are either known as primitive types (or just primitives) and object types (or just objects).

The next two paragraphs are going to be really boring, and I don't expect you to memorize what I am about to say. Your primitive types are your string, number, boolean, null, and undefined types. Any values that fall under their umbrella can't be divided any further. They are the jalapenos and mushrooms of the JavaScript world. Your object types are...or just is...the Object. Anything that you create or use that is an Object, under the covers, is potentially made up of other primitive types as well as other objects. Objects can also be empty, but we'll cover all those details eventually.

As you can see, primitives are pretty easy to understand. There is no depth to them, and you pretty much get what you see when you encounter one. Your object types are a bit more mysterious, so the last thing I want to cover before unleashing you with details about all of these types is what objects in JavaScript actually are.

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.

The Predefined Objects Roaming Around in JavaScript

Besides the built-in types you saw earlier, you also have a handful of predefined objects in JavaScript that you can use out-of-the-box. These objects allow you to work with everything from collections of data to dates to even text and numbers. Here is the table of these objects along with, just like before, a short blurb on what they do:

Type What it does
Array helps store, retrieve, and manipulate a collection of data
Boolean acts as a wrapper around the boolean primitive; still very much in love with true and false
Date allows you to more easily represent and work with dates
Function allows you to invoke some code among other esoteric things
Math the nerdy one in the group that helps you better work with numbers
Number acts as a wrapper around the number primitive
RegExp provides a lot of functionality for matching patterns in text
String acts as a wrapper around the string primitive

The way you use these built-in objects is a little bit different than how you use primitives. Each object has its own quirk on how you can use them as well. Explaining each object and how it is meant to be used is something that I will defer to for later, but here is a very short snippet of commented code to show you want is possible:

// an array
var names = ["Jerry", "Elaine", "George", "Kramer"];
var alsoNames = new Array("Dennis", "Frank", "Dee", "Mac");

// a round number
var roundNumber = Math.round("3.14");

// today's date
var today = new Date();

// a boolean object
var booleanObject = new Boolean(true);

// infinity
var unquantifiablyBigNumber = Number.POSITIVE_INFINITY;

// a string object
var hello = new String("Hello!");

One thing that you may find puzzling is the existence of the Object-form of the string, boolean, and number primitives. On the surface, the Object-form and primitive-form of these types look very similar. Here is an example:

var movie = "Pulp Fiction";
var movieObj = new String("Pulp Fiction");

alert(movie);
alert(movieObj);

What you will see printed will be identical. Below the surface, though, both movie and movieObj are very different. One is literally a primitive of type string, and the other is of type Object. This leads to some interesting (and possibly incomprehensible) behavior that I will gradually touch upon as we explore the handful of built-in types that you've seen so far.

Conclusion

If this feels like an abrupt ending where the movie stopped just as things were getting interesting, I don't blame you for thinking that way. All you really learned in this section are the names for the common built-in types and some basic background background material about all of them. What you are going to see in subsequent tutorials is a deeper look at all of these types and the nuances of working with them. Think of this tutorial as the gentle on-ramp that suddenly drops you into the rails of a crazy rollercoaster.

And by "crazy rollercoaster", I meant to say "the following tutorials":

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!!!