Book Author Validation
Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 52 of 56.
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:
- In the Book constructor, add an if-else check
- If the author is valid (an instance of Author class) using
author instanceof Author, setthis.#author = author - Otherwise (author is invalid): Log exactly
“Invalid author: must be Author instance”. Setthis.#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
1Objects & The this Keyword
Quick Review: ObjectsAdding Methods to ObjectsUnderstanding the this KeywordConstructor FunctionsThe new KeywordRecap Challenge7 Inheritance & The extends Key
InheritanceThe "is-a" RelationshipThe extends KeywordThe super() MethodInheriting Properties&MethodsRecap Challenge2Organizing Code
What are Modules?Exporting with exportImporting with importDefault vs. Named Exports8Organizing OOP Code
Organize Classes into Modules11Project: A Shape Renderer
Setup: Shape Class & ExportCircle Class Inheritance9Static Methods & Properties
Class-Level vs. Instance-LevelStatic PropertiesStatic Utility MethodsRecap challenge