What if you could create objects perfectly every time without repeating yourself?
Why Constructors in classes in Javascript? - Purpose & Use Cases
Imagine you want to create many objects representing different cars, each with its own color, model, and year. You write separate code to set these details every time you make a new car object.
Manually setting properties for each new object is slow and boring. It's easy to forget to add some details or make mistakes. If you want to change how cars are created, you must update every place where you set those details.
Constructors let you write one special function inside a class that runs automatically when you create a new object. This function sets up all the important details in one place, making your code cleaner and easier to manage.
const car1 = {};
car1.color = 'red';
car1.model = 'sedan';
car1.year = 2020;
const car2 = {};
car2.color = 'blue';
car2.model = 'SUV';
car2.year = 2022;class Car { constructor(color, model, year) { this.color = color; this.model = model; this.year = year; } } const car1 = new Car('red', 'sedan', 2020); const car2 = new Car('blue', 'SUV', 2022);
Constructors make creating many objects fast, consistent, and error-free by automating setup steps.
Think of a constructor like a recipe that automatically prepares a fresh cup of coffee every time you want one, so you don't have to remember each step every time.
Constructors run automatically when creating new objects.
They set up object properties in one place.
This saves time and reduces mistakes in your code.
Practice
constructor in a JavaScript class?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 usingthis.Final Answer:
To initialize new objects with default or given values -> Option CQuick Check:
Constructor = initialize object [OK]
- Confusing constructors with regular methods
- Thinking constructors delete objects
- Believing constructors create static properties
Solution
Step 1: Recall JavaScript class constructor syntax
In JavaScript classes, the constructor is defined as a method namedconstructorwithout thefunctionkeyword.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 AQuick Check:
Constructor method = constructor() { } [OK]
- Adding 'function' keyword before constructor
- Using arrow functions for constructors
- Using other language syntax like 'def'
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, ${this.name}!`;
}
}
const p = new Person('Alice');
console.log(p.greet());Solution
Step 1: Understand object creation with constructor
ThePersonclass constructor setsthis.nameto the passed argument. Here, 'Alice' is passed, sop.namebecomes 'Alice'.Step 2: Evaluate the greet method output
Thegreetmethod returns a string usingthis.name, which is 'Alice'. So,p.greet()returns 'Hello, Alice!'.Final Answer:
Hello, Alice! -> Option BQuick Check:
Constructor sets name, greet uses it = Hello, Alice! [OK]
- Forgetting to pass argument to constructor
- Expecting undefined because of missing this
- Thinking greet is not a method
class Car {
constructor(make, model) {
make = make;
model = model;
}
}Solution
Step 1: Review property assignment in constructor
Inside a constructor, to assign values to the object's properties, you must usethis.propertyName. Simply writingmake = make;assigns the parameter to itself, which does nothing.Step 2: Identify the correct fix
Usingthis.make = make;andthis.model = model;correctly assigns the values to the new object's properties.Final Answer:
Properties should be assigned usingthis, likethis.make = make;-> Option AQuick Check:
Use this.property = parameter [OK]
- Assigning parameters to themselves
- Not using this to set properties
- Thinking constructor must return explicitly
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?Solution
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.Final Answer:
constructor(title, author = 'Unknown') { this.title = title; this.author = author; } -> Option DQuick Check:
Optional param: param = default [OK]
- Using logical OR (||) which treats falsy as missing
- Omitting the optional parameter entirely
- Not providing a default, leaving undefined
Ready to prove it?
Pass the test and this pattern moves unknown
