0
0
Javascriptprogramming~15 mins

Constructor functions in Javascript - Mini Project: Build & Apply

Choose your learning style9 modes available
Building Objects with Constructor Functions
📖 Scenario: You are creating a simple system to keep track of books in a library. Each book has a title and an author.
🎯 Goal: You will build a constructor function to create book objects, then create a few books and display their details.
📋 What You'll Learn
Create a constructor function named Book that takes title and author as parameters
Create a variable named book1 using the Book constructor with title 'The Hobbit' and author 'J.R.R. Tolkien'
Create a variable named book2 using the Book constructor with title '1984' and author 'George Orwell'
Print the title and author of book1 and book2 using console.log
💡 Why This Matters
🌍 Real World
Constructor functions help create many similar objects easily, like books, users, or products in real applications.
💼 Career
Understanding constructor functions is important for JavaScript developers to organize and reuse code efficiently when working with objects.
Progress0 / 4 steps
1
Create the Book constructor function
Write a constructor function named Book that takes two parameters: title and author. Inside the function, assign this.title to title and this.author to author.
Javascript
Need a hint?

Use function Book(title, author) { ... } and inside assign this.title = title and this.author = author.

2
Create two book objects using the Book constructor
Create a variable named book1 and assign it a new Book object with title 'The Hobbit' and author 'J.R.R. Tolkien'. Then create a variable named book2 and assign it a new Book object with title '1984' and author 'George Orwell'.
Javascript
Need a hint?

Use const book1 = new Book('The Hobbit', 'J.R.R. Tolkien'); and similarly for book2.

3
Print the details of the books
Use console.log to print the title and author of book1 and book2. For example, print book1.title and book1.author on one line, and book2.title and book2.author on another line.
Javascript
Need a hint?

Use console.log(book1.title + ' by ' + book1.author); and similarly for book2.

4
Run the program to see the output
Run the program and observe the output. It should print the title and author of both books on separate lines.
Javascript
Need a hint?

The output should show the book titles and authors exactly as:
The Hobbit by J.R.R. Tolkien
1984 by George Orwell