Lesson Tuesday

When we look at Mozilla's documentation for JavaScript methods, we'll often see the term prototype. For instance, if we look up JavaScript's concat() method on Mozilla, we'll actually discover that there are two different concat() methods:

  • String.prototype.concat()
  • Array.prototype.concat()

We are familiar with strings and we will begin learning about arrays in the next lesson.

Before we do, we want to clear up some confusion about what a prototype is in JavaScript. We'll also cover prototypes in more detail in the next section on object-oriented JavaScript.

According to the Mozilla documentation:

Prototypes are the mechanism by which JavaScript objects inherit features from one another.

This is really all you need to know for now. Prototypes are just a way for an object to inherit functionality from another object.

When we refer to String.prototype.concat(), we are referring to a concat() method that all strings inherit. When we say Array.prototype.concat(), we are referring to a concat() method that all arrays inherit. Even though these methods have the same name, they are actually different methods. Sure, they do essentially the same thing: they put things together. When called on strings, they put two strings together. When called on arrays, they add something to the end of the array.

How do arrays or strings know how to concat()? Well, they have to be taught somehow. Just as a baby inherits certain traits when it is born, JavaScript objects inherit methods and properties when they are created. They do so through prototypal inheritance, a concept that boggles the minds of many experienced developers. For that reason, it's not necessary to dig into it too deeply right now.

So let's reiterate what we do need to know. We'll often see prototype in the following context: String.prototype.join(), Array.prototype.join(). In this case, prototype refers to a method that can be called on a type of object. This is relevant because we are about to add a different kind of object to our toolbox - arrays - and we need to be clear that arrays have a different set of methods than strings and other objects, even though these methods sometimes have the same names.

Also, from now on, when we introduce a new JavaScript method, we will do so just as the Mozilla documentation does. For instance, we'll state String.prototype.join() or Array.prototype.join(). We want to make sure you're not confused when we start doing this. It's just a way to make things clearer.

And if you really have to look into prototypal inheritance more to get a grasp on all of this, see the Mozilla documentation on Object prototypes.

Lesson 2 of 16
Last updated July 2, 2020