0
0
Javascriptprogramming~5 mins

Hoisting with let and const in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Hoisting with let and const
O(1)
Understanding Time Complexity

Let's explore how JavaScript handles variable declarations with let and const behind the scenes.

We want to understand how the program's steps grow when it runs with these variables.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function example() {
  console.log(a); // ReferenceError
  let a = 5;
  const b = 10;
  console.log(b);
}
example();
    

This code shows how let and const variables behave when accessed before declaration.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: There are no loops or repeated steps here.
  • How many times: The code runs a fixed number of steps once.
How Execution Grows With Input

Since there are no loops or repeated actions, the number of steps stays the same no matter what.

Input Size (n)Approx. Operations
105 steps
1005 steps
10005 steps

Pattern observation: The steps do not increase with input size; they stay constant.

Final Time Complexity

Time Complexity: O(1)

This means the program takes the same amount of time no matter how big the input is.

Common Mistake

[X] Wrong: "Accessing let or const variables before declaration works like var."

[OK] Correct: Unlike var, let and const are in a "temporal dead zone" before their declaration, causing errors if accessed early.

Interview Connect

Understanding how JavaScript handles variable declarations helps you write clearer code and avoid tricky bugs, a skill valuable in many coding situations.

Self-Check

"What if we replaced let and const with var? How would the time complexity and behavior change?"