Menu
Coddy logo textTech

Book Author Validation

Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 52 of 56.

challenge icon

Challenge

Improve the Book class constructor by adding validation. Currently, the Book accepts any value for the author parameter, but it should only accept an Author instance.

Your task:

  1. In the Book constructor, add an if-else check
  2. If the author is valid (an instance of Author class) using author instanceof Author, set this.#author = author
  3. Otherwise (author is invalid): Log exactly “Invalid author: must be Author instance”. Set this.#author = null

In this way, the book should still be created even with an invalid author.

Try it yourself

import { Author } from './Author.js';
import { Book } from './Book.js';

// Tests
const rowling = new Author('J.K. Rowling');

// Valid case (should work silently)
const validBook = new Book('Harry Potter', rowling);
console.log('Author:', validBook.authorInfo); // Should output: "Author: J.K. Rowling"

// Invalid cases (should log message but still create book)
const invalid1 = new Book('Fake Book', 'String Author');

All lessons in Object Oriented Programming