JavaScript Classes — Gotta Catch ’Em All!

Lisa Law
Coverwallet Engineering
8 min readAug 27, 2021

Picture credit: The Code Ninja, see this article

Currently, I’m halfway through my internship at CoverWallet. Before this internship, I worked mostly with Python and Django, whereas the stack I’m working with now is JavaScript and React. I spent the first three months understanding our project-internal logic, our task, familiarizing myself with the team and generally settling into the company. At CoverWallet, we look to build four core skills — leadership, communication, managerial and technical skills. After three months it was time for me to work on my technical skill set.

So I went and completed a couple of courses in JavaScript and React. As I worked my way through this udemy course, one exercise included creating monsters. It made me smile and I felt like straight away I would remember this lesson better.

I am also a huge Pokémon fan (or I used to be with the original 151 when you could still reasonably catch them all), and recently a friend’s son reminded me of this. He is 10 and as much into Pokémon as I used to be. Turns out, Pokémon are still going strong, so with the hope of attracting some #codenewbie to JavaScript, with this article I am proudly presenting an introduction to JavaScript classes.

Don’t worry, if you’re not into Pokémon, this article can still be valuable for you if you’re learning JavaScript!

TLDR for non-Pokémon fans: The idea of the Pokémon game is to wander around and catch little monsters called Pokémon. You can then make them attack other Pokémon and thus win over opponents and become the great super-mega-master Pokémon owner. You store your Pokémon in Pokeballs.

What are classes?

Classes are the prototype of objects. In a Platonian world, a class would be the idea of an object…. Wait, what? Let’s stick to Pokémon. We want to create a class called `Pokémon`, which defines qualities and powers that all Pokémon are going to possess.

So these are the first questions we need to ask ourselves: What powers do all Pokémon have? And what can all Pokémon do?

I came up with the following:

Classifying Pokémon

All Pokémon have

  • A name
  • A health score (or life force if you want). In the game, they are called HP — Health Points.
  • A classification (such as earth, water, electricity). In the game, this is the type.
  • An index number. This is the Pokédex number in the game.
  • An age. This doesn’t indicate how old the Pokémon really is, but shows how long it’s been since you’ve caught it.
  • A home. This could be a region, or a Pokeball after the Pokémon has been caught.

All Pokémon can

  • Flee
  • Enter a Pokeball
  • Exit a Pokeball
  • Attack
  • Heal

Ok, now that we have a basic understanding of what a Pokémon is and what it can do (any Pokémon!), what would this actually look like in JavaScript?

Pokémon classes — fields

The first thing we’re going to focus on is what a Pokémon has. Let’s have a look at the code below.

As you can see the first thing we do is write down the keyword `class`. This tells the compiler that we’re defining a new class. The next word `Pokemon` is your name for a class — you can name it whatever you want. Convention is to start class names with a capital letter.

The constructor method

In line 2 we’re introducing our `constructor` method. This method basically defines what the instances of your class have. It will get called every time a new instance is created, or, in other words, every time a new Pokémon enters the scene, it will have all the fields of the constructor method. You can choose not to define a customized constructor method, in which case a standard empty constructor will be passed to your class. If you are familiar with other programming languages, you can think of the constructor as `init()` or `initialize()`.

The constructor takes an argument which again you can name whatever you like. Since we’re talking about Pokémon here, I named it `characteristics`, it seemed fitting.

You could also destruct the object like so `constructor({ name, age, healthPoints, home, type, index })`. Note that then you would have to call `this.name = name` rather than referencing `characteristics` again.

`this` again

Anyone familiar with JavaScript will have come across the `this` keyword. It is featured in numerous memes and generally the nightmare of any #codenewbie. I won’t go into explaining it here, but it suffices to say that in our first bit of code, lines 3–8, `this` refers to the class we’ve just created.

Have you noticed that I initialized `healthPoints` differently? Instead of pulling the value from the characteristics object, I’ve given it a value straight away. This means that the starting value for each and every Pokémon we initialize will be 100, every Pokémon will be healthy to start with. In the arena, you will lose health points, and if you go to a Pokémon Center to heal your Pokémon, the health points will be set back to 100. We will talk more about this when we get to the `heal()` method.

Pokémon classes — methods

So now that we’ve declared what characteristics all Pokémon have, let’s see what all of them can do. Firstly, let’s define the `move()` method because it’s nice and simple.

Let’s have a look at lines 11–13. What’s happening here? We’re defining a new function called `flee`. Two noteworthy things here: we don’t need the `function` keyword here as we would need if we’re defining a function outside a class in ES5. We also don’t use the arrow structure here that is needed for ES6 functions outside of classes.

It just goes like this: the name of your function, followed by brackets (no space!) and then space, and curly braces. Within the curly braces, we will define our business logic.

In the case of `flee()` we will just return a string saying that the Pokemon fled. Pretty straightforward, right?

We’re also accessing the name of the particular Pokemon we will call the function on with `this.name`. We’ve wrapped it in what’s called a template literal: back ticks around the string and around the JS variable we’ll need the dollar sign and curly brackets. The output will then look like this:

If we tell a Pokemon called “pika” to flee, the output will be “pika just fled” and not “this.name just fled”. We’ll talk more about calling the class methods later.

Let’s have a look at all the methods we need for our Pokémon:

As you can see, `enterPokeball()` and `exitPokeball()` follow the same pattern as `flee()`. There isn’t much to them. Note however that we don’t need a comma separation between each method!

Let’s have a look at the healing and attacking, they look a little bit more interesting.

`heal()` includes a condition. If the Pokémon is already full on health points, there is no need to heal it! We will just remind the player of that. In all other cases, we are setting the health points back to 100, the initial value. We are accessing the Pokémon’s health points the same way as before via `this.healthPoints`.

The `attack()` method affects another Pokémon’s health points. As you can see in line 31, we’re subtracting 10 points from the opponent’s health points via `opponent.healthPoints`.

But what’s happening in line 30? Here we are defining a new Pokémon that will be the default opponent if the attack function gets called without specifying an opponent. So whenever we call `attack()`, the program will automatically create a new opponent with the name “EvilPokemon” and health points = (100–10). Remember we set the initial health points to 100 for all Pokemon?

Note that if we don’t specify the rest of the constructor options, such as age, home and index, these will be undefined.

Calling on Pokémon

Finally, how do we actually create one specific Pokemon? This part of the code is pretty simple, we’ve already done the hard part.

You can start with the variable keyword `let` or `const` and the name of your new Pokémon. I chose “pika” but you could name it any way you want. Next, the keyword `new` is followed by the name of the class. Note that the convention is to set the name in lowercase and the class is, as described above, starting with a capital letter (it needs to be the same as in line 1).

Next, we pass an object with the curly braces and we pass in all the properties we specified in the constructor method. You can give arbitrary values. Note that if you don’t specify a property, it will be undefined. Did you notice that we didn’t include `healthPoints`? They will automatically be set to 100 so we don’t need to specifically include them on initialization.

Your newly created Pokémon will have access to all the methods we specified before. It can attack, flee, heal, and enter / exit their Pokeball. Simply put `pika.heal()` and see what happens!

Now, go extend your reach to the stars above! Why not create your own Pokémon class? Would you include the same fields and methods?

Unfortunately, I don’t get to work with Pokémon in my everyday life. At CoverWallet I’m part of the Checkout team, and we handle payments and accompany the customer through the final steps of their purchase. But who knows, maybe you’ll soon see a Charmander hopping over the CoverWallet checkout page. You need to make sure to go through the whole flow though, right up to and including the payment. Who knows what might cross your path! Gotta catch ’em all!

For reference, find the full code in this codepen.

--

--

Lisa Law
Coverwallet Engineering

programmer, world traveler, linguist. Karate 2nd kyu, beginner Muay Thai fighter, bouldering enthusiast.