Instance methods in Javascript - Time & Space Complexity
Let's see how the time it takes to run instance methods changes as we use more data.
We want to know how the work grows when calling methods on objects.
Analyze the time complexity of the following code snippet.
class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count += 1;
}
incrementBy(n) {
for (let i = 0; i < n; i++) {
this.increment();
}
}
}
This code defines a class with methods to increase a count, either by 1 or by a given number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop inside
incrementBycallsincrementrepeatedly. - How many times: The loop runs
ntimes, wherenis the input toincrementBy.
Each time we increase n, the loop runs that many times, so the work grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to increment |
| 100 | 100 calls to increment |
| 1000 | 1000 calls to increment |
Pattern observation: The number of operations grows evenly as n grows.
Time Complexity: O(n)
This means the time to run incrementBy grows in a straight line with the input size.
[X] Wrong: "Calling increment inside the loop makes it slower than linear time."
[OK] Correct: Each increment call is simple and constant time, so repeating it n times still grows linearly.
Understanding how instance methods run helps you explain how your code scales when working with objects and their data.
"What if incrementBy called increment twice inside the loop? How would the time complexity change?"
Practice
Solution
Step 1: Understand class components
A class can have variables (properties) and functions (methods).Step 2: Identify instance methods
Instance methods are functions inside the class that use object data.Final Answer:
A function defined inside a class that works with object data -> Option DQuick Check:
Instance method = function inside class using object data [OK]
- Confusing instance methods with variables
- Thinking instance methods run without objects
- Mixing instance methods with static methods
greet inside a JavaScript class?Solution
Step 1: Recall instance method syntax
Inside a class, instance methods are defined by name followed by parentheses and braces without thefunctionkeyword.Step 2: Check each option
greet() { console.log('Hello'); } matches this syntax. function greet() { console.log('Hello'); } wrongly usesfunction. var greet = () => { console.log('Hello'); } uses variable syntax outside class method style. static greet() { console.log('Hello'); } defines a static method, not instance.Final Answer:
greet() { console.log('Hello'); } -> Option BQuick Check:
Instance method syntax = name() { ... } [OK]
- Adding 'function' keyword inside class methods
- Using arrow functions as instance methods
- Confusing static and instance method syntax
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hi, I am ${this.name}`;
}
}
const p = new Person('Anna');
console.log(p.greet());Solution
Step 1: Understand object creation
ThePersonclass setsthis.nameto 'Anna' when creatingp.Step 2: Call the instance method
Thegreetmethod returns a string usingthis.name, which is 'Anna'.Final Answer:
Hi, I am Anna -> Option AQuick Check:
Method uses this.name = 'Anna' so output matches [OK]
- Forgetting to use 'this' inside methods
- Calling method without creating object
- Expecting method to print instead of return
class Car {
constructor(model) {
this.model = model;
}
showModel() {
console.log(model);
}
}
const c = new Car('Tesla');
c.showModel();Solution
Step 1: Check variable usage in method
The method tries to printmodelbut it is not defined locally or globally.Step 2: Use 'this' to access object property
Inside methods, object properties must be accessed withthis.model.Final Answer:
Missing 'this' before model in showModel method -> Option CQuick Check:
Access object data with this.property [OK]
- Omitting 'this' before property names
- Confusing local variables with object properties
- Thinking constructor parameters are not allowed
Counter that counts how many times its method increment is called on each object separately. Which code correctly implements this behavior?Solution
Step 1: Understand instance vs static properties
Each object needs its owncount, so it must be an instance property set in the constructor.Step 2: Check increment method
The method should increasethis.countand return it. class Counter { constructor() { this.count = 0; } increment() { this.count++; return this.count; } } does this correctly.Step 3: Identify errors in other options
class Counter { static count = 0; increment() { Counter.count++; return Counter.count; } } uses static property shared by all objects. class Counter { constructor() { this.count = 0; } increment() { count++; return count; } } uses undefinedcountvariable. class Counter { increment() { this.count = this.count + 1; return this.count; } } does not initializecountbefore incrementing.Final Answer:
class Counter { constructor() { this.count = 0; } increment() { this.count++; return this.count; } } -> Option AQuick Check:
Instance property in constructor + method updates it [OK]
- Using static properties for per-object data
- Not initializing properties before use
- Incrementing undefined variables
Ready to prove it?
Pass the test and this pattern moves unknown
