JavaScript · Syntax · Beginner

OOP Basics

11 tasks

Practical exercises on the basics of OOP in JavaScript: creating classes and objects, properties, methods, constructors, changing object state, and simple entity modeling.

Classes and objects — the idea

#
A class is a blueprint. An object is what you build from that blueprint. The same class can produce many objects, each with its own independent data. ```javascript class BankAccount { constructor(balance) { this.balance = balance; } } const acc1 = new BankAccount(100); const acc2 = new BankAccount(500); console.log(acc1.balance); // 100 console.log(acc2.balance); // 500 ``` acc1 and acc2 are independent objects. Changing acc1.balance does not affect acc2. Classes group two things together: data (properties) and behaviour (methods). A method is a function defined inside the class body. This grouping is the main idea behind object-oriented programming — keep the data and the code that works with it in the same place. If you have used Python, note that what Python calls self, JavaScript calls this. What Python calls __init__, JavaScript calls constructor. The concept is identical; only the syntax differs.

constructor and this

#
constructor is the method JavaScript calls automatically when you create a new object with new. It sets up the initial state of the instance. ```javascript class Rectangle { constructor(width, height) { this.width = width; this.height = height; } } const r = new Rectangle(3, 4); console.log(r.width, r.height); // 3 4 ``` this refers to the object being created. When you write this.width = width, you are storing the value on the object itself — not in a local variable that disappears when constructor finishes. Every property you want the object to remember must be assigned to this. Unlike Python's self, you do not declare this as a parameter — JavaScript provides it automatically inside any method. ```javascript class Rectangle { constructor(width, height) { this.width = width; this.height = height; } area() { return this.width * this.height; } } const r = new Rectangle(3, 4); console.log(r.area()); // 12 ``` Methods in a JavaScript class are defined without the function keyword — just the name and parentheses. Inside the method, this gives access to the object's own properties.

Common class patterns

#
A method that modifies the object's state — returns nothing, just changes a property: ```javascript class Counter { constructor(value) { this.value = value; } increment() { this.value++; } } const c = new Counter(0); c.increment(); c.increment(); console.log(c.value); // 2 ``` A method that checks a condition and returns a boolean: ```javascript class Person { constructor(name, age) { this.name = name; this.age = age; } isAdult() { return this.age >= 18; } } ``` A method that computes from the properties and returns a value: ```javascript class Temperature { constructor(celsius) { this.celsius = celsius; } toFahrenheit() { return this.celsius * 9 / 5 + 32; } } ``` A method that modifies state with a parameter: ```javascript class BankAccount { constructor(balance) { this.balance = balance; } deposit(amount) { this.balance += amount; } } ``` The pattern is always the same: access what you need through this, compute or modify, return only when there is a meaningful value to return.
01

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;
    }
}
02

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}`);
03

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;
    }
}
04

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());
05

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());
06

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());
07

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;
        }
    }
}
08

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());
09

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());
10

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);
11

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);