Class syntax in Javascript - Time & Space Complexity
Let's see how the time it takes to run code using JavaScript classes changes as we create more objects or call methods.
We want to know how the work grows when using class syntax for multiple objects.
Analyze the time complexity of the following code snippet.
class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count++;
}
}
const counters = [];
for (let i = 0; i < n; i++) {
counters.push(new Counter());
}
This code creates n Counter objects, each starting with a count of zero.
- Primary operation: Creating a new Counter object inside a loop.
- How many times: The loop runs
ntimes, creatingnobjects.
Each time we increase n, we create more objects, so the work grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations |
| 100 | 100 object creations |
| 1000 | 1000 object creations |
Pattern observation: The work grows evenly as we add more objects.
Time Complexity: O(n)
This means the time to create all objects grows in a straight line as we add more objects.
[X] Wrong: "Creating objects inside a loop is instant and does not depend on how many objects we make."
[OK] Correct: Each object takes some time to create, so more objects mean more total time.
Understanding how creating many objects affects time helps you write efficient code and explain your choices clearly.
"What if the increment method was called inside the loop for each object? How would the time complexity change?"
Practice
class in JavaScript?Solution
Step 1: Understand what a class represents
A class is a blueprint or template for creating objects that share properties and behaviors.Step 2: Compare options with the definition
Only To create blueprints for objects with shared properties and methods correctly describes the purpose of a class in JavaScript.Final Answer:
To create blueprints for objects with shared properties and methods -> Option AQuick Check:
Class purpose = blueprint for objects [OK]
- Confusing classes with functions that run immediately
- Thinking classes store data like databases
- Mixing classes with styling or HTML
Car with a constructor?Solution
Step 1: Recall correct class syntax
A class is declared with the keywordclass, followed by the class name and curly braces. The constructor is a method inside without thefunctionkeyword.Step 2: Check each option
Onlyclass Car { constructor() { } }is correct. The other options have syntax errors such as parentheses after the class name, usingfunction Car()declaration, or using thefunctionkeyword for the constructor.Final Answer:
class Car { constructor() { } } -> Option DQuick Check:
Class syntax = class Name { constructor() {} } [OK]
- Adding parentheses after class name
- Using 'function' keyword inside class methods
- Defining constructor outside class body
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, ${this.name}!`;
}
}
const p = new Person('Anna');
console.log(p.greet());Solution
Step 1: Understand object creation and constructor
ThePersonclass constructor setsthis.nameto the passed argument. Here, 'Anna' is passed, sothis.namebecomes 'Anna'.Step 2: Call the greet method
Thegreetmethod returns a string usingthis.name. Sincethis.nameis 'Anna', the returned string is 'Hello, Anna!'.Final Answer:
Hello, Anna! -> Option AQuick Check:
Method uses this.name = 'Anna' [OK]
- Forgetting to pass argument to constructor
- Expecting greet to print instead of return
- Confusing this.name with undefined
class Animal {
constructor(type) {
this.type = type;
}
speak() {
console.log('I am a ' + type);
}
}
const a = new Animal('Dog');
a.speak();Solution
Step 1: Check variable usage inside speak method
The method usestypedirectly, buttypeis not defined in its scope. It should usethis.typeto access the instance property.Step 2: Confirm other parts are correct
The constructor and class syntax are correct, and creating an instance withnewis valid.Final Answer:
Using undefined variable 'type' inside speak method -> Option CQuick Check:
Use this.type to access property inside methods [OK]
- Using variable name without this inside methods
- Forgetting to use new keyword when creating instance
- Misnaming constructor method
console.log(car.getDescription());? class Vehicle {
constructor(make, model) {
this.make = make;
this.model = model;
}
getDescription() {
return `${this.make} ${this.model}`;
}
}
class Car extends Vehicle {
constructor(make, model, year) {
super(make, model);
this.year = year;
}
getDescription() {
return `${this.year} ${super.getDescription()}`;
}
}
const car = new Car('Toyota', 'Corolla', 2020);
console.log(car.getDescription());Solution
Step 1: Understand inheritance and super calls
TheCarclass extendsVehicle. TheCarconstructor callssuper(make, model)to initialize those properties in the parent class.Step 2: Analyze getDescription method in Car
TheCarclass overridesgetDescriptionand callssuper.getDescription()to get the parent class description, then prepends the year.Step 3: Substitute values
super.getDescription()returns 'Toyota Corolla'. Addingthis.year(2020) before it results in '2020 Toyota Corolla'.Final Answer:
2020 Toyota Corolla -> Option BQuick Check:
super.method() calls parent method [OK]
- Forgetting to call super() in subclass constructor
- Not using super.getDescription() inside overridden method
- Mixing order of make and model in output
Ready to prove it?
Pass the test and this pattern moves unknown
