Bootcamp Notes – Day 1 (Mon) – React: More JavaScript – Objects and Classes
More JavaScript – Objects and Classes
Using Template Literals
Template literals provide another, typically quicker way to combine variables with strings. For example, with this code:
const foxSpeed = "quick";
const foxColor = "brown";
const foxAction = "jumps";
const dogType = "lazy";
If you were to use these variables within a string using the concatenation operator (+) as you have done before, it would look like this:
"The " + foxSpeed + " " + foxColor + " fox " + foxAction + " over the " + dogType + " dog."
Whew. That’s a lot to type. With template literal syntax, you can write the same thing like this, using backticks around the entire string and ${ … }s around the variables being interpolated:
`The ${foxSpeed} ${foxColor} fox ${foxAction} over the ${dogType} dog.`;
Notice that instead of single or double quotes, the string inside which you are using template literals is surrounded by pairs of backticks (`). The backticks allow you to insert variables inside the string (a.k.a. string interpolation) with the ${ … } syntax.
Template Literals Example in CodePen
Objects
Recall, JavaScript has eight data types:
- Number – (Primitive data types)
- String – (Primitive data types)
- Boolean – (Primitive data types)
- Object – (not considered a primitive)
- Undefined – (Primitive data types)
- Null – (Primitive data types)
- Symbol – (Primitive data types)
- BigInt – (Primitive data types)
We will learn about the Object data type. Object is the only data type that is not considered a primitive. It is really a data structure for a collection of data than a singular piece of data. It is really a collection of data. We can create an object and put it into a variable with a name just like any other variable. We can also create variables and functions that belong to that object and these special variables and functions are called properties and methods and they can only be used by referring to that object. Objects can have properties and methods which are – which are variables and functions that “belong” to that object.
Creating an object with properties
Here is an example of an object with just properties first. Let us say we are writing a game and we have a monster in the game. Let us say a dragon.. So we are going to make an object for the dragon. It is going to start out just like we’re making a variable declaration and then we are going to use curly braces to surround what’s called the object literal, which is how we create the object. This is similar to how when you create an array using square brackets to surround the array items and that is actually called an array literal.
const dragon1 = {color: “red” , maxHP: 1000};
No when we write objects, it’s common to put everything on separate lines like this. We are defining the properties that belong to this dragon!
const dragon1 = {
color: “red”,
maxHP: 1000
};
So now that we have created this dragon, we can type the variable name that we used for the object into the console log:
So we can see what is inside the variable dragon1 . We can query the properties that belong to it by using dot notation and the way that we can do that is by typing the name of the object then a dot then the property name.
There is a second way that we can get to a property. which is by using bracket notation instead of dot notation. But typically it’s longer to type and dot notation is preferable. There are cases when bracket notation is useful, but we won’t cover that right now. Bracket notation example below:
As you can see, you can bundle a lot of related data together into a single object.
Arrays VS Objects
You learned before that arrays are a special type of object. Arrays are not as flexible as objects. They can have items just as objects can have properties, but the array items are always accessed by a numeric index like this example:
Where as for objects, the properties are accessed by the property names which are configured by you to whatever you want them to be.
.
Another way that objects are more flexible is that you can add custom methods to objects. Arrays and Objects both have methods, but you can add custom methods to objects! Arrays have predefined methods as part of the JavaScript language, such as array.join(), array.pop() that are already written for you and you can use them on any array. However with objects you can add your own custom method.
For example, let’s say that we wanted a method named dragon.roar and we wanted to see the message “The dragon roars ferociously”
Here is how we can do this:
Object Methods
Objects can also have methods.
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.
A method is a function stored as a property.
Look at this example:
The two ways are equivalent. While you should use the shorthand syntax that was shown with dragon2, you should be aware of the older syntax because you will still encounter it in older codebases. Also, if you need to add or update a method after the object has already been declared, you will need to use the older syntax.
Add and update object properties and methods
Let’ say we want to add an element property to our dragon1 object. We want this dragon to be a fire dragon. Follow theses steps in your console.
You may have noticed something strange happening — we have been changing object variables that were declared as constants. How is this possible? For now, understand that unlike other data types, objects that are declared as constants can be changed – at least, their properties and methods can. However, you can never re-assign the entire value of a constant object.
Even if you declare an object variable with the const keyword, the properties and methods of that object can be changed. But the variable can never be reassigned.
As you can see above, you cannot reassign the entire object variable. However, it is fine to update the properties and values.
This is true of arrays as well, because arrays are a special type of object. You cannot reassign the whole array. But you can change items in the array.
Method Parameters
You can use parameters in methods just as you can in functions.
What is This
In a function definition, this
refers to the “owner” of the function. It stands for the object that is the owner of the method. this keyword can be used inside object methods to reference the object itself when referring to properties of the same object.
JavaScript Classes
The word class in JavaScript (and in programming languages in general) means something completely different from the word class used in HTML and CSS. Classes in JavaScript are templates for objects. They let you create multiple instances of an object easily. Classes are not unique to JavaScript. They are part of the Object Oriented Programming (OOP) paradigm and are found in many programming languages not just JavaScript.
Let’s look how we can make dragons more easily using classes.
Creating a Class
Class Constructors and Properties
Class Instances and the New Keyword
class Dragon {
constructor(color, maxHP) { <=== The constructor is a special class method that will say what we want the default properties of our class to be.
this.color = color;
this.maxHP = maxHP;
}
}
const dragon1 = new Dragon(“red” , 1200); <== Each time we make one of these it creates an instance of the dragon class.
We now have our dragon class. This is a template from which we can make as many dragons as you want. To do this we will use the new keyword. The new keyword creates the new object and it passes these argument values into the class constructor and there they become properties of a new object through assigning them as values of this dot property name.
Class Methods
We can also add default methods to classes but we won’t use the constructor for that. Instead the way that you add them or like pretty much identical to the way that you add them to a single object.
Note: React.js has its own way of using JavaScript classes in what are called React Class Components. Some of the syntax will be the same, but there will be differences. Still, it will be useful for you to understand the underlying JavaScript that those Class Components are based on.
Class Inheritance
Class Inheritance: We can create child classes based on parent classes. The child class inherits the properties and methods of the parent class. Also, a child class can also add its own properties and methods without affecting the parent class. Typically, parent classes are more general. Child classes are typically more specific.
So maybe we have monster class instead of a dragon class. As you can see from our example below, extends keyword is the way that you can make a child class.
You can see below that is has inherited the roar method from the monster class.
Codepen Example of Class Inheritance
The super method and inheriting properties
Remember, for any class to store default properties, it must have a constructor method.
The super method is a special method for child constructors to pass those properties that are inherited from the parent class to be initialized in the constructor there. You must use it with inherited properties, properties that are defined in the parent class’s constructor.
You can see that the dragon1 object has received the roar() method and the isScary property from the parent class, and also has its own fly() method which can access the type, color, and element
Like the dragon, the werewolf can roar, and it has the isScary variable set to true. But unlike the dragon, the werewolf can howl(), but it cannot fly().
Now you can see how useful class inheritance can be: When you have multiple classes that will share some of the properties and methods, but not all, you can set up a parent class for the shared properties and methods and reuse that code.
Default Function Parameters
The default function parameters is a useful addition in es6 JavaScript. JavaScript allows you to call functions without providing arguments for all parameters. This can come in handy when you are defining a class.
You can use default function parameters in the class constructor. Here is an example.
As you can see by running the above code in your console, when an object was created from the Cat class with just the name, the default color of “gray” was applied. But when an object was created from the Cat class with both the name and color passed in, the passed-in color was used instead of the default.
Additional Resources:
- MDN – Template literals
- W3Schools – JavaScript Objects
- JavaScript.info – Objects
- MDN – JavaScript object basics
- Eloquent JS – The Secret Life of Objects
- W3Schools – The JavaScript This Keyword
- JavaScript.info – this in methods
- MDN – this
- Alligator.io – A Quick Reference to This
- W3Schools – JavaScript Classes
- JavaScript.info – Classes
- MDN – Classes
- W3Schools – Classes (scroll down to section on Inheritance)
- JavaScript.info – Class inheritance
- MDN – Classes – Sub-classing with extends
- MDN – Default function parameters
- MDN – Object initializer
- JavaScript.info – Object