Hoisting with let and const in Javascript - Time & Space 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.
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 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.
Since there are no loops or repeated actions, the number of steps stays the same no matter what.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 5 steps |
| 100 | 5 steps |
| 1000 | 5 steps |
Pattern observation: The steps do not increase with input size; they stay constant.
Time Complexity: O(1)
This means the program takes the same amount of time no matter how big the input is.
[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.
Understanding how JavaScript handles variable declarations helps you write clearer code and avoid tricky bugs, a skill valuable in many coding situations.
"What if we replaced let and const with var? How would the time complexity and behavior change?"