Exercise 1: Class Implementation

Test your class implementation skills by solving this challenge.

Problem statement

Implement a class Book in JavaScript that produces the expected result as given in the sample input and output section. Some steps involved in class implementation are given below.

  1. Define the constructor.
  2. Define the class methods.
  3. Define the properties.

The object of the Book class is instantiated like so:

const book = new Book('Who Moved My Cheese?', 'Spencer Johnson', 96);

Sample input and output

The book object should be able to give the following results given in the output column on the respective input calls.

Input Output
console.log(book.title); Who Moved My Cheese
console.log(book.pages); 96
try { book.pages = 96; } catch(ex) { console.log(ex.message); } Cannot set property pages of #< Book> which has only a getter
console.log(book.copiesSold); 0
book.copiesSold = 1; console.log(book.copiesSold); 1
try { book.copiesSold = -2; } catch(ex) { console.log(ex.message);} Value can’t be negative
console.log(book.copiesSold); 1

Exercise

Complete this exercise to test your knowledge and skills of class implementation.

Get hands-on with 1200+ tech skills courses.