What this keyword represents in Javascript - Time & Space Complexity
We want to understand how the use of the this keyword affects the speed of JavaScript code.
Specifically, we ask: how does accessing this inside functions impact the number of operations as input grows?
Analyze the time complexity of the following code snippet.
function countItems(arr) {
let count = 0;
for (let i = 0; i < arr.length; i++) {
if (this.isValid(arr[i])) {
count++;
}
}
return count;
}
const validator = {
isValid(item) { return item > 0; }
};
countItems.call(validator, [1, 2, 3, 4]);
This code counts how many items in an array pass a test using this to call a method.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array with
for. - How many times: Once for each item in the array (n times).
Each item in the array is checked once using this.isValid. As the array grows, the number of checks grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items checked, regardless of using this.
[X] Wrong: "Using this inside the loop makes the code slower in a way that changes the time complexity."
[OK] Correct: Accessing this is just a reference to an object and does not add extra loops or nested work. It does not change how the number of operations grows with input size.
Understanding how this works helps you write clear and efficient code. Knowing it does not add hidden costs shows you can reason about performance calmly and confidently.
"What if the isValid method called inside the loop was asynchronous? How would the time complexity change?"
Practice
this keyword represent inside a regular function in JavaScript when called as a method of an object?Solution
Step 1: Understand method call context
When a function is called as a method of an object,thisrefers to that object.Step 2: Apply to example
Inside the method,thispoints to the object owning the method, not the global object or function itself.Final Answer:
The object that owns the method -> Option AQuick Check:
thisin method = owning object [OK]
this is the object before the dot [OK]- Thinking
thisalways points to global object - Confusing
thiswith the function itself - Assuming
thisis undefined in methods
this inside an arrow function to refer to the surrounding object?Solution
Step 1: Understand arrow function
Arrow functions do not have their ownthisbehaviorthis; they inherit it from the surrounding scope.Step 2: Apply to object method
Usingthisinside an arrow function refers to thethisof the outer function or object context.Final Answer:
Arrow functions do not have their ownthis, so it inherits from the surrounding scope -> Option DQuick Check:
Arrow functionthis= inherited context [OK]
this from outside [OK]- Assuming arrow functions have their own
this - Using arrow functions as object methods expecting
thisto be the object - Confusing arrow function
thiswith regular functionthis
const obj = {
name: 'Alice',
greet() {
console.log(this.name);
}
};
const greetFunc = obj.greet;
greetFunc();What will be the output when
greetFunc() is called?Solution
Step 1: Understand function reference assignment
Assigningobj.greettogreetFuncdetaches the method from its object.Step 2: Call context of
When called alone,greetFunc()thisinsidegreetFuncis the global object or undefined in strict mode, sothis.nameis undefined.Final Answer:
undefined -> Option BQuick Check:
Detached methodthis= undefined [OK]
this [OK]- Expecting
thisto still point to the object - Thinking it prints the name property
- Ignoring strict mode effects on
this
const person = {
name: 'Bob',
sayName: () => {
console.log(this.name);
}
};
person.sayName();Solution
Step 1: Analyze arrow function
Arrow functions do not have their ownthisbehaviorthis; they inherit from the outer scope, which is notperson.Step 2: Effect on
Sinceconsole.log(this.name)thisis notperson,this.nameis undefined or from global scope, not 'Bob'.Final Answer:
thisinside arrow function does not refer toperson-> Option AQuick Check:
Arrow functionthis≠ object [OK]
this [OK]- Thinking arrow functions bind
thisto object - Assuming syntax error due to arrow function
- Confusing missing parentheses with
thisissues
Car that sets the make property using this. Which code correctly uses this to assign the property when creating a new car?Solution
Step 1: Understand constructor function usage
Constructor functions usethisto assign properties to the new object created bynew.Step 2: Check each option
function Car(make) { this.make = make; } const myCar = new Car('Toyota'); correctly assignsthis.make = makeand usesnewto create an object. function Car(make) { make = this; } const myCar = Car('Toyota'); assigns incorrectly. const Car = (make) => { this.make = make; }; const myCar = new Car('Toyota'); uses arrow function which does not bindthis. function Car(make) { this.make = make; } const myCar = Car('Toyota'); calls constructor withoutnew, sothisis not the new object.Final Answer:
function Car(make) { this.make = make; } const myCar = new Car('Toyota'); -> Option CQuick Check:
Constructorthisneedsnew[OK]
new with constructor to bind this correctly [OK]- Calling constructor without
new - Using arrow functions as constructors
- Assigning
make = thisinstead ofthis.make = make
Ready to prove it?
Pass the test and this pattern moves unknown
