- Abstraction
- AI Pair Programming
- Algorithm
- API
- Array
- Array methods
- Booleans
- Callback
- Class
- Class Members
- Closure
- Closure
- Code refactoring
- Comment
- Computer programming
- Conditional statements
- Constant
- Constructor
- Coupling and Cohesion
- Data types
- Debugging
- Decorator
- Dependency
- Destructuring
- Dictionary
- Enum
- Event
- Exception / Error handling
- Function
- Generic / Template
- Higher-order function
- IDE
- Immutability
- Inheritance
- Input validation
- Integer
- Interface
- Iteration patterns
- Legacy code
- Loop
- Machine learning
- Memoization
- Memory and references
- Method
- Module
- Null / Undefined / None
- Null safety / Optional values
- Object
- Object-Oriented Programming (OOP)
- Operator
- Parameter
- Parsing
- Promise and Async/Await
- Prompt Engineering
- Recursion
- Regular expression
- Return statement
- Rollback
- Runtime
- Scope
- Script
- Sequence
- Set
- Spaghetti code
- Spread and Rest operators
- State management
- String
- Switch statement
- Synchronous vs Asynchronous execution
- Syntax
- Technical debt
- Ternary operator
- Testing
- This / Self
- Tuple
- Type casting
- Type conversion
- Variable
- Vibe coding
- Webhook
PROGRAMMING-CONCEPTS
Constructor: Definition, Purpose, and Examples
A constructor is a special method that runs automatically when you create a new object. Its job is to set up the object’s initial state — things like starting values, configuration options, or required data. Constructors help make sure every new instance begins life fully prepared to do its job.
Although the idea is shared across languages, the syntax varies: JavaScript/TypeScript use a constructor method, Python uses __init__, and Swift uses init. Regardless of name, they all serve the same purpose: building the object and giving it the values it needs.
What a Constructor Does
A constructor always runs when a new instance is created. It typically:
- assigns initial values
- prepares internal data structures
- validates input
- sets up connections or listeners (in UI or async contexts)
You can think of it as the moment an object “comes to life.”
Constructors in JavaScript and TypeScript
JavaScript and TypeScript classes use the constructor keyword.
This method runs as soon as you call new ClassName().
Example: Setting Up a Geometry Shape
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
const box = new Rectangle(4, 6);
box.area(); // 24
The constructor stores width and height on the new instance.
Without those assignments, the area() method would have no data to work with.
Adding Validation Inside the Constructor
class Temperature {
constructor(private celsius: number) {
if (celsius < -273.15) {
throw new Error("Temperature cannot go below absolute zero.");
}
}
toFahrenheit() {
return (this.celsius * 9) / 5 + 32;
}
}
Here, the constructor enforces a rule: no value below absolute zero.
TypeScript’s access modifiers (private) help structure the instance cleanly.
Constructors in Python
Python's constructor method is named __init__.
This method receives the instance as self, followed by any arguments.
Example: Setting Starting Inventory
Python
class StockItem:
def __init__(self, name, quantity):
self.name = name
self.quantity = quantity
def restock(self, amount):
self.quantity += amount
Each StockItem instance gets its own name and starting quantity.
When you create a new item, Python runs __init__ automatically with those values.
Default Values in Python Constructors
Python
class Report:
def __init__(self, title, format="pdf"):
self.title = title
self.format = format
Default arguments allow flexible object creation without multiple constructor overloads.
Constructors in Swift
Swift uses the init keyword.
The constructor must ensure every stored property has a value.
Example: Player Stats
class Player {
var score: Int
var nickname: String
init(score: Int = 0, nickname: String) {
self.score = score
self.nickname = nickname
}
}
Swift requires all stored properties (score, nickname) to be initialized before the constructor finishes.
Default values make it easier to create multiple variations.
Swift Convenience Initializers
Swift allows additional constructors called convenience initializers:
class ColorSwatch {
var hex: String
init(hex: String) {
self.hex = hex
}
convenience init(red: Int, green: Int, blue: Int) {
let hexValue = String(format: "#%02X%02X%02X", red, green, blue)
self.init(hex: hexValue)
}
}
Convenience initializers help construct the same object using different parameter formats.
Constructors in React Components
React function components don’t have constructors by default, but class components do.
They often store initial state or bind methods.
React Class Component Constructor
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { time: new Date() };
}
render() {
return <p>{this.state.time.toLocaleTimeString()}</p>;
}
}
The super(props) call ensures the parent class (React.Component) initializes correctly.
Then the constructor sets the initial state.
Most modern React code prefers function components + hooks, but understanding class constructors is still useful.
Why Constructors Exist
Constructors support predictable setup.
When you create an object, you know:
- which values it will have
- that required fields are present
- that internal structures are ready
- that the instance is safe to use immediately
Without constructors, you’d need to run a separate setup function every time, which is error-prone.
Real-World Examples and Why They Matter
Below are fresh, practical examples that show how constructors shape real systems.
Example 1: API Client Configuration (JavaScript)
class ApiClient {
constructor(baseUrl) {
this.baseUrl = baseUrl;
}
async get(path) {
const res = await fetch(`${this.baseUrl}${path}`);
return res.json();
}
}
const client = new ApiClient("https://example.com");
client.get("/status");
The constructor stores the base URL for all requests.
This creates a reusable, configurable client.
Example 2: Generating Unique IDs (Python)
Python
import uuid
class Session:
def __init__(self):
self.id = uuid.uuid4()
Each new session gets a unique ID automatically.
The constructor ensures no two sessions collide.
Example 3: Game Character Loadout (Swift)
class Loadout {
var weapons: [String]
init(defaults: [String]) {
self.weapons = defaults
}
}
let soldier = Loadout(defaults: ["Rifle", "Grenade"]);
The constructor prepares the character with a starting set of equipment.
Every instance begins with predictable data.
Common Mistakes with Constructors
Forgetting to Assign Properties
Creating a parameter but failing to save it to the instance leads to undefined or missing data later.
Doing Too Much Work
Constructors should prepare the object, not perform heavy tasks like network calls.
Infinite Recursion in Swift
Using self too early in initialization can create cycles.
Forgetting super() in JavaScript/TypeScript
Derived classes must call super() before using this.
Summary
A constructor is the method that runs when an object is created.
It sets initial values, performs validation, and ensures the instance begins in a usable state.
JavaScript/TypeScript use constructor, Python uses __init__, Swift uses init, and React class components use constructors to initialize state.
Once you understand how constructors shape an object’s starting conditions, you gain much more control over how your programs behave from the moment they run.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.