Access modifiers public private protected in Typescript - Time & Space Complexity
Let's see how using access modifiers affects the speed of running TypeScript code.
We want to know if public, private, or protected changes how long the program takes as it grows.
Analyze the time complexity of the following code snippet.
class Counter {
private count = 0;
public increment() {
this.count++;
}
protected getCount() {
return this.count;
}
}
const counter = new Counter();
for (let i = 0; i < 1000; i++) {
counter.increment();
}
This code defines a class with public, private, and protected parts, then calls a method many times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop calling
increment()1000 times. - How many times: Exactly 1000 times, each increasing the count by one.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments |
| 100 | 100 increments |
| 1000 | 1000 increments |
Pattern observation: The number of operations grows directly with the number of increments.
Time Complexity: O(n)
This means the time to run grows in a straight line as the number of increments grows.
[X] Wrong: "Using private or protected slows down the code because of extra checks."
[OK] Correct: Access modifiers are for organizing code and controlling access, but they do not add extra time when running loops or methods.
Understanding that access modifiers do not affect how fast your code runs helps you focus on writing clear and safe code without worrying about speed.
"What if the increment method called another method inside the class multiple times? How would the time complexity change?"
Practice
Solution
Step 1: Understand access modifiers
publicmeans anyone can access the member,privaterestricts access to the class only, andprotectedallows access to the class and its subclasses.Step 2: Identify the modifier allowing access from anywhere
Onlypublicallows access from outside the class, including other classes and code.Final Answer:
public -> Option BQuick Check:
public = accessible everywhere [OK]
- Confusing private with public access
- Thinking protected is accessible outside class
- Assuming readonly controls access
age in a TypeScript class?Solution
Step 1: Recall TypeScript property declaration syntax
Access modifiers come before the property name and type, e.g.,private age: number;.Step 2: Identify correct modifier placement
private age: number;correctly placesprivatebefore the property name and type.age: private number;has incorrect order.Final Answer:
private age: number; -> Option AQuick Check:
Modifier before name and type [OK]
- Placing modifier after property name
- Using invalid syntax like 'age: private number;'
- Confusing protected and private keywords
class Animal {
protected sound = 'Roar';
}
class Lion extends Animal {
public makeSound() {
return this.sound;
}
}
const lion = new Lion();
console.log(lion.makeSound());Solution
Step 1: Understand protected access
The propertysoundisprotected, so it can be accessed inside the class and its subclasses likeLion.Step 2: Trace method call and output
ThemakeSoundmethod returnsthis.sound, which is "Roar". So,console.logprints "Roar".Final Answer:
"Roar" -> Option CQuick Check:
Protected allows subclass access [OK]
- Thinking protected is inaccessible outside class
- Confusing private with protected
- Expecting runtime error for protected access
class Person {
private name: string = 'Alice';
}
const p = new Person();
console.log(p.name);Solution
Step 1: Check access modifier usage
The propertynameis declaredprivate, so it cannot be accessed outside the classPerson.Step 2: Analyze the console.log statement
Trying to accessp.nameoutside the class causes a compile-time error about private access.Final Answer:
Error: Cannot access private property 'name' outside class -> Option DQuick Check:
Private blocks outside access [OK]
- Assuming private properties are accessible outside
- Confusing private with protected
- Expecting code to print property value
class Vehicle {
protected speed: number = 0;
private engineOn: boolean = false;
public start() {
this.engineOn = true;
}
}
class Car extends Vehicle {
public accelerate() {
this.speed += 10; // Line 1
this.engineOn = true; // Line 2
}
}
const car = new Car();
car.accelerate();Solution
Step 1: Understand access levels of properties
speedisprotected, so accessible in subclassCar.engineOnisprivate, accessible only insideVehicle.Step 2: Analyze lines in subclass method
Line 1 accessesspeedand is valid. Line 2 tries to accessengineOndirectly, which causes a compilation error.Final Answer:
Line 2: Accessing private property 'engineOn' in subclass -> Option AQuick Check:
Private blocks subclass access [OK]
- Assuming private is accessible in subclasses
- Thinking protected is private
- Ignoring error on private property access
Ready to prove it?
Pass the test and this pattern moves unknown
