JavaScript · Syntax · Beginner
OOP Basics
Practical exercises on the basics of OOP in JavaScript: creating classes and objects, properties, methods, constructors, changing object state, and simple entity modeling.
Quick topic start and explanations before exercises (exercises below):
constructor and this
#Common class patterns
#Exercises:
User class with a name.
#Create a User class with a name property. Create an object of this class and print its name.
class User {
// your code here
}
let user = new User("Alex");
console.log(user.name);
Solution
class User {
constructor(name) {
this.name = name;
}
}
let user = new User("Alex");
console.log(user.name);
// or you can create a method that returns the name
class User {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
Car class: brand and year.
#Create a Car class with brand and year properties. Create an object and print the string: "Car: Toyota, 2020"
class Car {
// your code here
}
Solution
class Car {
constructor(brand, year) {
this.brand = brand;
this.year = year;
}
}
let car = new Car("Toyota", 2020);
console.log(`Car: ${car.brand}, ${car.year}`);
Counter with increment.
#Create a Counter class with a value property. Add an increment method that increases the value by 1.
class Counter {
// your code here
}
let c = new Counter(0);
c.increment();
console.log(c.value);
Solution
class Counter {
constructor(value) {
this.value = value;
}
increment() {
this.value += 1;
}
}
let c = new Counter(0);
c.increment();
console.log(c.value);
// or you can make increment return the new value
class Counter {
constructor() {
this.value = 0;
}
increment() {
this.value += 1;
return this.value;
}
}
Rectangle area.
#Create a Rectangle class with width and height properties. Add an area method that returns the area.
class Rectangle {
// your code here
}
let rectangle = new Rectangle(3, 4);
console.log(rectangle.area());
Solution
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
let rectangle = new Rectangle(3, 4);
console.log(rectangle.area());
Greeting with a class method.
#Create a Greeting class with a sayHello method that returns the string "Hello!".
class Greeting {
// your code here
}
let greeting = new Greeting();
console.log(greeting.sayHello());
Solution
class Greeting {
sayHello() {
return "Hello!";
}
}
let greeting = new Greeting();
console.log(greeting.sayHello());
Adult age check.
#Create a Person class with name and age properties. Add an isAdult method that returns true if the age is 18 or older.
class Person {
// your code here
}
let person = new Person("John", 20);
console.log(person.isAdult());
Solution
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
isAdult() {
return this.age >= 18;
}
}
let person = new Person("John", 20);
console.log(person.isAdult());
Bank account deposit.
#Create a BankAccount class with a balance property. Add a deposit method that increases the balance.
class BankAccount {
// your code here
}
let account = new BankAccount(100);
account.deposit(50);
console.log(account.balance);
Solution
class BankAccount {
constructor(balance) {
this.balance = balance;
}
deposit(amount) {
this.balance += amount;
}
}
let account = new BankAccount(100);
account.deposit(50);
console.log(account.balance);
// or you can explicitly prevent depositing a negative amount
class BankAccount {
constructor(balance) {
this.balance = balance;
}
deposit(amount) {
if (amount > 0) {
this.balance += amount;
}
}
}
Convert Celsius to Fahrenheit.
#Create a Temperature class with a celsius property. Add a toFahrenheit method that returns the temperature in degrees Fahrenheit. Formula: celsius * 9 / 5 + 32.
class Temperature {
// your code here
}
let temperature = new Temperature(0);
console.log(temperature.toFahrenheit());
Solution
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
toFahrenheit() {
return this.celsius * 9 / 5 + 32;
}
}
let temperature = new Temperature(0);
console.log(temperature.toFahrenheit());
Message length method.
#Create a Message class with a text property. Add a getLength method that returns the message length.
class Message {
// your code here
}
let message = new Message("Hello world");
console.log(message.getLength());
Solution
class Message {
constructor(text) {
this.text = text;
}
getLength() {
return this.text.length;
}
}
let message = new Message("Hello world");
console.log(message.getLength());
Timer with adding seconds.
#Create a Timer class with a seconds property. Add an addTime method that increases the time by the specified number of seconds.
class Timer {
// your code here
}
let timer = new Timer(10);
timer.addTime(5);
console.log(timer.seconds);
Solution
class Timer {
constructor(seconds) {
this.seconds = seconds;
}
addTime(extra) {
this.seconds += extra;
}
}
let timer = new Timer(10);
timer.addTime(5);
console.log(timer.seconds);
Formatter class for strings.
#Write a Formatter class with a string property on the object. When creating an instance of the class, the string is passed into the constructor and stored in this.string. The class must have several methods that return a modified version of this string: - the trim(length) method returns the string cut to the specified length and adds "[...]" at the end. The length of these added symbols must also be counted. - the truncate(length) method returns the string cut to the specified length, but it does not break words and instead cuts at the last space within the specified length. IMPORTANT: - the original string in this.string must remain unchanged; - do not create separate properties for results, return new values from methods; - you may create helper properties, for example for the string "[...]"; - inside methods you may use regular local variables, not everything needs to be stored in this.
class Formatter {
constructor(string) {
// your code here
}
trim(length) {
// your code here
}
truncate(length) {
// your code here
}
}
let x = new Formatter("This string is used here only as an example and has no other meaning.");
console.log(x.trim(15));
console.log(x.truncate(15));
console.log(x.string);
let y = new Formatter("Hooray, I did it!.");
console.log(y.trim(8));
console.log(y.truncate(3));
console.log(y.string);
Solution
class Formatter {
constructor(string) {
this.string = string;
this.end = "[...]";
}
trim(length) {
if (length <= this.end.length) {
return this.end.slice(0, length);
}
return this.string.slice(0, length - this.end.length) + this.end;
}
truncate(length) {
const part = this.string.slice(0, length);
const lastSpace = part.lastIndexOf(" ");
return lastSpace === -1 ? part : part.slice(0, lastSpace);
}
}
let x = new Formatter("This string is used here only as an example and has no other meaning.");
console.log(x.trim(15));
console.log(x.truncate(15));
console.log(x.string);
let y = new Formatter("Hooray, I did it!.");
console.log(y.trim(8));
console.log(y.truncate(3));
console.log(y.string);