Mark As Completed Discussion

Introduction

In everyday life, we can list a thing's qualities and attributes whenever we have to describe it. For example, describing a certain book involves specifying its title, publication year, ISBN, author, and the number of pages. This collection of information comes together and helps specify an instance of a book

This concept also exists in programming, where we can create bundles of information as objects. Each object has certain attributes, and a particular instance of the object has certain values for the attributes. A class specifies the blueprint of an object and its behavior. This lesson will expand on how classes and objects work, how to create and use them, and how their implementation differs in JavaScript and TypeScript.

Classes and Objects

As described above, a class describes what data an object can hold and what it can do with that data. For example, consider we have to create a Book object and store the data mentioned in the example above. But first, we have to specify what a Book object looks like, i.e. declare a Book class.

In the class declaration, we specify the following:

  • the variables that will store data (attributes)

  • a function that gets called whenever we create a new object (constructor)

  • function(s) that can access the attributes and use the values for processing (methods)

Attributes

Going back to the earlier example, the Book class will have an attribute to store each of the information:

  • Title

  • Publication year

  • ISBN

  • Author name

  • Number of pages

The following diagram shows different Book objects and how they are bundles of data. Notice how different objects can have same values for many of the attributes.

Attributes

Constructor

The constructor creates an object and has to set the values for the attributes for an object instance. It can also do other things such as call other functions or perform computations. A class can have multiple constructors too, and it decides which one to call based on how we pass data.

For the Bookclass example, let's have two constructor functions: one that has parameters and one that doesn’t. The definition of the constructors and how to call them is shown below.

Constructor

Methods

A class declaration can have functions that can process the data stored in an object’s attributes. Once an object gets created, a class method can be called through it. For the Book class example, let’s create a method called paperbackOrHardcover() that returns ‘hardcover’ if the pages of the book are more than 500 and ‘paperback’ if it is less. The definition of this method and how it is called is shown below.

Methods

Are you sure you're getting this? Click the correct answer from the options.

Given the following code, what output will the line console.log of code print?

JAVASCRIPT
1class Book {
2	constructor(title, author, ISBN, numberOfPages, publicationYear) {
3		this.title = title;
4		this.author = author;
5		this.ISBN = ISBN;
6		this.numberOfPages = numberOfPages;
7		this.publicationYear = publicationYear;
8	}
9	get title() {
10		return this._title
11	}
12	set title(value) {
13		this._title = value
14	}
15}
16let myBook = new Book('Life of Pi', 'Yann Martel', 9780156027328, 352, 2001)
17let myBook2 = new Book('Life of Sky', 'Yann Martel', 9780156027328, 352, 2001)
18myBook2.title = myBook.title
19console.log(myBook.title)

Click the option that best answers the question.

  • Life of Pi
  • Life of Sky
  • No output
  • Error

Classes and Objects in JavaScript

We can define classes in JavaScript through the class keyword. Since JavaScript is a dynamic programming language, the methods and functions in a class can refer to and set values of attributes (called properties in JavaScript) not even declared. For example, the definition of the Book class and how to create a new Book object in JavaScript is shown below.

JAVASCRIPT
1class Book {
2	constructor(title, author, ISBN, numberOfPages, publicationYear) {
3		this.title = title;
4		this.author = author;
5		this.ISBN = ISBN;
6		this.numberOfPages = numberOfPages;
7		this.publicationYear = publicationYear;
8	}
9	paperbackOrHardcover() {
10		if this.numberOfPages > 500 {
11			return 'hardcover'
12		} else {
13			return 'paperback'
14		}
15	}
16}
17let myBook = new Book(‘Life of Pi’, ‘Yann Martel’, 9780156027328, 352, 2001)
18console.log(myBook.paperbackOrHardcover())
19// prints 'paperback' for the myBook object

Here, we create the Bookclass definition and then create a Bookobject instance with the new keyword. Then, we print the result of paperbackOrHardcover()method to the console.

Note: Always use the new keyword to create a new object instance.

Methods that retrieve or set an attribute value can be designated with the get and set keywords. This avoids confusion since the method name is the same as the attribute name.

Notice these methods reference the property value through this._title instead of the regular this.title, as shown below. This is to avoid confusion since the method name is the same as the attribute name.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Let's test your knowledge. Is this statement true or false?

We want to create a Person object with the following respective values for its properties:

  • name: John
  • age: 18
  • height: 182

Assuming it has a basic class definition and constructor, does the following piece of code successfully create the object and print its name to the console?

JAVASCRIPT
1let myPerson = Person('John', 18, 182)
2console.log(myPerson.name)

Press true if you believe the statement is correct, or false otherwise.

Classes and Objects in TypeScript

The syntax for classes and objects in TypeScript is mostly the same as in JavaScript. However, TypeScript requires that the properties of objects and their types be declared in the class definition. The following example shows how to define the Book class and declare its properties in TypeScript.

TEXT/TYPESCRIPT
1class Book {
2	title: string;
3	author: string;
4	ISBN: integer;
5	numberOfPages: integer;
6	publicationYear: integer;
7	constructor(title, author, ISBN, numberOfPages, publicationYear) {
8		this.title = title;
9		this.author = author;
10		this.ISBN = ISBN;
11		this.numberOfPages = numberOfPages;
12		this.publicationYear = publicationYear;
13	}
14}

TypeScript also allows for properties to have default values if the constructor doesn’t assign any, as shown in the following example.

Note: All properties need to be initialized either in the class or the constructor.

TEXT/TYPESCRIPT
1class Book {
2	title: string;
3	author: string;
4	ISBN: integer;
5	numberOfPages: integer;
6	publicationYear = 2022;
7	constructor(title, author, ISBN, numberOfPages, publicationYear) {
8		this.title = title;
9		this.author = author;
10		this.ISBN = ISBN;
11		this.numberOfPages = numberOfPages;
12		this.publicationYear = publicationYear;
13	}
14}

It can get tiring to write constructors for classes when all they do is set the value for properties with the same name as the parameters. The example above shows how repetitive the constructor definition can get. TypeScript comes with a feature called parameter properties that allows for properties to get declared while being the constructor’s parameters.

For example, the above class definition can be rewritten with parameter properties, as shown below. The public keyword specifies that we can access these properties directly through the objects.

TEXT/TYPESCRIPT
1class Book {
2	constructor(
3		public title: string,
4		public author: string, 
5		public ISBN: integer, 
6		public numberOfPages: integer, 
7		public publicationYear: integer
8	) {}
9}

Class methods in TypeScript can be defined as arrow functions so that we can directly access their values. The following example shows a getter method in TypeScript.

TEXT/TYPESCRIPT
1class Book {
2	constructor(
3		public title: string,
4		public author: string, 
5		public ISBN: integer, 
6		public numberOfPages: integer, 
7		public publicationYear: integer
8	) {}
9	getTitle = () => {
10		return this.title
11	}
12}
13let myBook = new Book(‘Life of Pi’, ‘Yann Martel’, 9780156027328, 352, 2001)
14console.log(myBook.getTitle())
15// prints ‘Life of Pi’ for the myBook object

Lets see if you understood how classes and objects work in TypeScript.

Build your intuition. Is this statement true or false?

The following piece of code shows a Car class, its properties, and its constructor. However, it doesn't initialize all properties in the constructor. Will the following piece of TypeScript code successfully go through?

TEXT/TYPESCRIPT
1class Car {
2  name: string;
3  model: string;
4  objectInstantiatedAtDate: Date;
5
6  constructor(name: string, model:string) {
7    this.name = name;
8    this.model = model;
9  }
10}

Press true if you believe the statement is correct, or false otherwise.

Classes and Objects: JavaScript vs. TypeScript

As mentioned, JavaScript and TypeScript mostly have similar syntaxes for classes and objects. After all, all TypeScript code gets transpiled (translated) to JavaScript code and executed. However, there are a few main differences highlighted in the table given in the diagram below.

Classes and Objects: JavaScript vs. TypeScript

Try this exercise. Click the correct answer from the options.

What language does the following piece of code belong to?

TEXT/TYPESCRIPT
1class Person {
2  name: string;
3  lastName: string;
4  birthDate = new Date();
5
6  constructor(name: string, lastName: string) {
7    this.name = name;
8    this.lastName = lastName;
9  }
10}

Click the option that best answers the question.

  • Typescript
  • Javascript

Summary

In this lesson, we talked about important programming concepts like classes and objects, defining classes and their methods, creating objects, and using them. Classes are super helpful for making a codebase modular and easy to follow. They also make it easy to map a real-world problem to a programming context (as we saw in the Book class example). A class' object makes managing data easier since it is bundled into manageable bits.

One Pager Cheat Sheet

  • We can create objects with certain attributes that represent particular instances using a class, which will be explained in this lesson for JavaScript and TypeScript.
  • Classes provide structure to create objects that store data and define how it is used.
  • The Book class stores important attributes such as Title, Publication Year, ISBN, Author Name and Number of Pages in order to create different Book objects with various values.
  • The constructor of a class defines the parameters required to create a new object instance and sets values for the attributes of that object.
  • Calling the paperbackOrHardcover() method of a Book object will determine whether the book is a hardcover or paperback.
  • The output of the console.log() statement is Life of Pi, which is the value of the title attribute of myBook, initialized using its constructor and subsequently set equal to that of myBook2.
  • We can use the class and new keywords in JavaScript to define objects and create instances, respectively, where the methods can refer to and set values of properties, while get and set keywords can clarify the relationship between methods and properties.
  • To successfully create the object, the new keyword needs to be used when creating it, and then the name property can be printed to the console.
  • In TypeScript, classes and objects use the same syntax as JavaScript and require that the properties of objects and their types be declared in the class definition and further services like parameter properties and arrow functions can be used to simplify the code.
  • All properties in a TypeScript class must be initialized either in the class or the constructor.
  • TypeScript adds some features such as Access Modifiers and Accessors to the traditional JavaScript structure of Classes and Objects.
  • The code is written in Typescript due to its syntax and use of the constructor and : notation to declare properties.
  • Classes and objects allow developers to easily break down a real-world problem into manageable and modular components, making it easier to manage data.