0
0
Javascriptprogramming~5 mins

this in global scope in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: this in global scope
O(1)
Understanding Time Complexity

Let's explore how the keyword this behaves when used in the global scope in JavaScript.

We want to understand what this points to and how it affects code execution.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


console.log(this);

function showThis() {
  console.log(this);
}

showThis();
    

This code logs the value of this in the global scope and inside a regular function call.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: There are no loops or repeated operations here.
  • How many times: The code runs a few simple statements once each.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
10About 3 operations
100About 3 operations
1000About 3 operations

Pattern observation: The number of operations stays the same no matter how big the input is because there are no loops or repeated steps.

Final Time Complexity

Time Complexity: O(1)

This means the code runs in constant time, doing the same small number of steps regardless of input size.

Common Mistake

[X] Wrong: "this always points to the global object no matter where it is used."

[OK] Correct: Inside functions, this can point to different things depending on how the function is called, not always the global object.

Interview Connect

Understanding how this works in different scopes is a key skill that shows you know how JavaScript handles context, which helps you write clearer and bug-free code.

Self-Check

"What if we changed the regular function to an arrow function? How would the value of this change inside the function?"