0
0
Javascriptprogramming~15 mins

Constructors in classes in Javascript - Mini Project: Build & Apply

Choose your learning style9 modes available
Constructors in Classes
📖 Scenario: You are creating a simple program to keep track of pets in a pet store. Each pet has a name and an age.
🎯 Goal: Build a class called Pet that uses a constructor to set the pet's name and age. Then create a pet object and display its details.
📋 What You'll Learn
Create a class named Pet
Add a constructor method with parameters name and age
Inside the constructor, assign name and age to the object properties
Create an instance of Pet with name Buddy and age 3
Print the pet's name and age using the instance
💡 Why This Matters
🌍 Real World
Classes with constructors are used to create objects that represent real things, like pets, users, or products, with their own data.
💼 Career
Understanding constructors is essential for building organized and reusable code in many programming jobs, especially in web development.
Progress0 / 4 steps
1
Create the Pet class
Write a class called Pet with an empty constructor method.
Javascript
Need a hint?

Use the class keyword followed by Pet. Inside, add constructor() with empty braces.

2
Add parameters and assign properties in the constructor
Modify the constructor to accept parameters name and age. Inside the constructor, assign this.name = name and this.age = age.
Javascript
Need a hint?

Inside the constructor, use this.name = name and this.age = age to store the values.

3
Create a Pet instance
Create a variable called myPet and assign it a new Pet object with name "Buddy" and age 3.
Javascript
Need a hint?

Use new Pet("Buddy", 3) to create the object and assign it to myPet.

4
Print the pet's name and age
Write a console.log statement to print myPet.name and myPet.age separated by a space.
Javascript
Need a hint?

Use console.log(myPet.name + " " + myPet.age) to print the values.