12. Of Pizza, Types, Primitives, and Objects

This Chapter

  • Understand what all this fuss about Objects is about

  • Learn about the basic types you’ll run into in JavaScript

  • Find out that pizza has an educational value beyond just being deliciously awesome

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

Following are some examples to jog our memory:

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

Unlike other languages, JavaScript makes it really easy to specify and use these built-in things. We 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 us. Knowing these details is important because it will not only help us make sense of our code more easily, it may even help us 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 chapter, you are going to get a gentle introduction to what they are.

Onward!

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:

Image

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

Image

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:

Image

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:

Image

Unfortunately for all of us, there is no one simple ingredient called cheese or pepperoni out there. We need to combine and prepare and add some more ingredients to make up some of the complex ingredients we 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 we 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 in JavaScript. Each individual ingredient could be considered a counterpart to a type that you can use (Figure 12.1).

Image

FIGURE 12.1

A list of the simple types we have in JavaScript.

Just like the cheese, sauce, pepperoni, mushrooms, and bacon in our version of a pizza, the types in JavaScript are string, number, boolean, null, undefined, bigint, symbol, 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 chapters, the Table 12.1 provides a very brief summary of what they do.

TABLE 12.1 Types

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 sort of 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
bigint Allows you to work with really large or really small numbers that go beyond what a typical “number” might support
symbol Something unique and immutable (can’t be changed) that you can optionally use as an identifier for Object properties
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 our pizza’s simple and complex ingredients, our 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 our types in JavaScript are either known as primitive types (or just primitives) and object types (or just objects).

Our primitive types are string, number, boolean, null, bigint, symbol, 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. Primitives are pretty easy to define and bucket into something understandable. There is no depth to them, and we pretty much get what we see when we encounter one.

Our object types, represented by Object in our table, are a bit more mysterious, so the last thing we 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. A poster you got on eBay is also an object. I could go on forever, but (for everyone’s sake) I’m going to stop here.

Some objects like a paperweight don’t do much:

Image

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

Image

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. Table 12.2 lists these objects along with, just like before, a short blurb on what they do:

TABLE 12.2 Objects

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 what is possible:

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

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

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

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

// infinity
let unquantifiablyBigNumber = Number.POSITIVE_INFINITY;

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

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

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

console.log(movie);
console.log(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 we’ve seen so far.

The Absolute Minimum

If this feels like a movie that abruptly ended just as things were getting interesting, I don’t blame you for thinking that way. The main takeaway is that your primitives make up the most basic types that you can use in your code. Your objects are a bit more complex and are made up of other primitives or objects. We’ll see more of that in a little bit when we dive deeper. Beyond that, we learned the names for the common built-in types and some basic background material about all of them.

What you are going to see in subsequent chapters is a deeper look at all of these types and the nuances of working with them. Think of this chapter as the gentle on-ramp that suddenly drops you onto the rails of a crazy rollercoaster.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.147.190