📖 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
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
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
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
Hint
Use console.log(myPet.name + " " + myPet.age) to print the values.
Practice
(1/5)
1. What is the main purpose of a constructor in a JavaScript class?
easy
A. To create static properties for the class
B. To define methods that all objects share
C. To initialize new objects with default or given values
D. To delete objects when they are no longer needed
Solution
Step 1: Understand the role of a constructor
A constructor is a special method in a class that runs automatically when a new object is created.
Step 2: Identify what constructors do
Constructors set initial values for the object's properties using this.
Final Answer:
To initialize new objects with default or given values -> Option C
Quick Check:
Constructor = initialize object [OK]
Hint: Constructors always set up new objects [OK]
Common Mistakes:
Confusing constructors with regular methods
Thinking constructors delete objects
Believing constructors create static properties
2. Which of the following is the correct syntax to define a constructor inside a JavaScript class?
easy
A. constructor() { this.name = 'John'; }
B. function constructor() { this.name = 'John'; }
C. def constructor() { this.name = 'John'; }
D. constructor = () => { this.name = 'John'; }
Solution
Step 1: Recall JavaScript class constructor syntax
In JavaScript classes, the constructor is defined as a method named constructor without the function keyword.
Step 2: Check each option
constructor() { this.name = 'John'; } uses the correct syntax: constructor() { ... }. Options B and C incorrectly use keywords from other languages or function syntax. constructor = () => { this.name = 'John'; } uses arrow function syntax, which is invalid for constructors.
Final Answer:
constructor() { this.name = 'John'; } -> Option A
Quick Check:
Constructor method = constructor() { } [OK]
Hint: Constructor is a method named exactly 'constructor' [OK]
Common Mistakes:
Adding 'function' keyword before constructor
Using arrow functions for constructors
Using other language syntax like 'def'
3. What will be the output of the following code?
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, ${this.name}!`;
}
}
const p = new Person('Alice');
console.log(p.greet());
medium
A. Hello, undefined!
B. Hello, Alice!
C. Hello, !
D. TypeError: p.greet is not a function
Solution
Step 1: Understand object creation with constructor
The Person class constructor sets this.name to the passed argument. Here, 'Alice' is passed, so p.name becomes 'Alice'.
Step 2: Evaluate the greet method output
The greet method returns a string using this.name, which is 'Alice'. So, p.greet() returns 'Hello, Alice!'.
Final Answer:
Hello, Alice! -> Option B
Quick Check:
Constructor sets name, greet uses it = Hello, Alice! [OK]
Hint: Constructor sets property, method uses it [OK]
Common Mistakes:
Forgetting to pass argument to constructor
Expecting undefined because of missing this
Thinking greet is not a method
4. Identify the error in this class definition:
class Car {
constructor(make, model) {
make = make;
model = model;
}
}
medium
A. Properties should be assigned using this, like this.make = make;
B. The class name should be lowercase
C. The constructor should not have parameters
D. The constructor must return an object explicitly
Solution
Step 1: Review property assignment in constructor
Inside a constructor, to assign values to the object's properties, you must use this.propertyName. Simply writing make = make; assigns the parameter to itself, which does nothing.
Step 2: Identify the correct fix
Using this.make = make; and this.model = model; correctly assigns the values to the new object's properties.
Final Answer:
Properties should be assigned using this, like this.make = make; -> Option A
Quick Check:
Use this.property = parameter [OK]
Hint: Always use this.property to assign inside constructor [OK]
Common Mistakes:
Assigning parameters to themselves
Not using this to set properties
Thinking constructor must return explicitly
5. You want to create a Book class where each book has a title and an optional author. If no author is given, it should default to 'Unknown'. Which constructor correctly implements this behavior?
hard
A. constructor(title, author) { this.title = title; if (author) this.author = author; }
Step 1: Understand optional parameters in constructors
Use default parameter values for optional arguments. constructor(title, author = 'Unknown') { this.title = title; this.author = author; }: constructor(title, author = 'Unknown') sets author to 'Unknown' if not provided or undefined, but keeps passed falsy values like empty string.
Step 2: Check other options
B uses ||, which defaults falsy values (not just missing). C has no author param. D sets only if truthy, else undefined.