this in functions in Javascript - Time & Space Complexity
Let's explore how the use of this inside functions affects the time it takes for code to run.
We want to see how the number of operations changes as the input grows when this is involved.
Analyze the time complexity of the following code snippet.
function countItems(arr) {
let count = 0;
arr.forEach(function() {
count++;
});
return count;
}
const items = [1, 2, 3, 4, 5];
countItems(items);
This code counts how many items are in an array using a function where this is not explicitly used.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forEachloop runs once for each item in the array. - How many times: It runs exactly as many times as there are items in the array.
As the array gets bigger, the function runs the counting step more times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of operations grows directly with the number of items.
Time Complexity: O(n)
This means the time to run the function grows in a straight line as the input size grows.
[X] Wrong: "Using this inside the function makes it slower or more complex."
[OK] Correct: The use of this does not add extra loops or repeated steps; it just changes what the function refers to, so it does not affect time complexity.
Understanding how this works in functions helps you reason about code behavior and performance clearly, a skill valuable in many coding discussions.
"What if we replaced the regular function with an arrow function that uses this? How would the time complexity change?"
Practice
this refer to inside a regular function called as obj.method()?Solution
Step 1: Understand how
When a function is called as a method of an object,thisworks in method callsthispoints to that object.Step 2: Apply to the example
Sinceobj.method()methodis called byobj,thisinsidemethodrefers toobj.Final Answer:
The objectobjthat calls the method -> Option DQuick Check:
obj.method()meansthis = obj[OK]
this is the caller object in method calls [OK]- Thinking
thisis always global - Confusing
thiswith the function itself - Assuming
thisis undefined in method calls
this refers to the object?Solution
Step 1: Understand function types and
Arrow functions do not have their ownthisthis; they inherit from the outer scope. Regular functions have their ownthis.Step 2: Check each option
A uses arrow function, sothisis inherited from outer scope (global), not the object. B uses concise method syntax, which bindsthisto the object. C uses invalid syntax (cannot define concise method with arrow). D uses invalid syntax (function() =>not valid).Final Answer:
const obj = { method() { console.log(this); } }; -> Option CQuick Check:
Use concise method syntax for object methods [OK]
this in objects [OK]- Using arrow functions for object methods expecting
thisas object - Attempting invalid concise arrow syntax like
method() => {} - Using invalid syntax like
function() => {}inside object
const obj = {
name: 'Alice',
greet() {
function inner() {
console.log(this.name);
}
inner();
}
};
obj.greet();Solution
Step 1: Analyze
The functionthisinsideinnerfunctioninneris a regular function called without an object, sothisinside it is undefined in strict mode (or global object in non-strict).Step 2: Check what
Sincethis.nameprintsthisis undefined,this.nameisundefined, soconsole.logprintsundefined.Final Answer:
undefined -> Option AQuick Check:
Inner function called alone:this = undefined[OK]
this undefined [OK]- Assuming
thisinside inner function is the object - Expecting 'Alice' to print
- Confusing arrow functions with regular functions
this.name inside inner refers to obj.const obj = {
name: 'Bob',
greet() {
function inner() {
console.log(this.name);
}
inner();
}
};
obj.greet();Solution
Step 1: Understand why
Becausethisis wrong insideinnerinneris a regular function called alone,thisis undefined, notobj.Step 2: Explore fixes to bind
Changethiscorrectlyinnerto an arrow function: Using arrow function forinnerinheritsthisfromgreet, which isobj. Bindinnertothisusinginner.bind(this)(): Usinginner.bind(this)()explicitly setsthistoobj. Assignconst self = thisand useself.nameinsideinner: Savingthisinselfand usingself.nameworks becauseselfis accessible insideinner.Step 3: Conclusion
All three methods correctly fix the problem.Final Answer:
All of the above -> Option BQuick Check:
Bind or arrow or self variable fixesthis[OK]
this in inner functions [OK]- Only trying one fix and missing others
- Not understanding arrow functions inherit
this - Forgetting to call
bindmethod
counter with a method count that increases a number every second and logs it using this.value. Which code correctly keeps this referring to counter inside setInterval callback?const counter = {
value: 0,
count() {
setInterval(function() {
this.value++;
console.log(this.value);
}, 1000);
}
};
counter.count();Solution
Step 1: Identify the problem with
The callback function is a regular function, sothisinsetIntervalthisinside it is notcounterbut undefined or global object.Step 2: Explore solutions to keep
Replace the callback with an arrow function:thisascountersetInterval(() => { this.value++; console.log(this.value); }, 1000);: Arrow functions inheritthisfromcount, sothis.valueworks. Bindthisto the callback:setInterval(function() { ... }.bind(this), 1000);: Usingbind(this)explicitly setsthisinside callback. Saveconst self = thisbeforesetIntervaland useself.valueinside callback: Savingthisinselfand usingself.valueworks becauseselfis accessible inside callback.Step 3: Conclusion
All three methods correctly keepthisreferring tocounter.Final Answer:
All of the above -> Option AQuick Check:
Arrow, bind, or self variable all fixthisin callbacks [OK]
this in callbacks [OK]- Using regular function without binding
this - Expecting
thisto becounterautomatically - Not saving
thisbefore callback
Ready to prove it?
Pass the test and this pattern moves unknown
