Variable hoisting behavior in Javascript - Time & Space Complexity
Let's explore how variable hoisting affects the speed of running JavaScript code.
We want to see how the number of steps changes when variables are hoisted.
Analyze the time complexity of the following code snippet.
function example(arr) {
for (let i = 0; i < arr.length; i++) {
var temp = arr[i] * 2;
console.log(temp);
}
}
This code loops through an array, doubles each item, and prints it. The variable temp is declared inside the loop using var.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop runs through each item in the array. - How many times: It runs once for every element in the array, so as many times as the array length.
As the array gets bigger, the loop runs more times, doing the same steps each time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 times the steps inside the loop |
| 100 | About 100 times the steps inside the loop |
| 1000 | About 1000 times the steps inside the loop |
Pattern observation: The work grows directly with the size of the input array.
Time Complexity: O(n)
This means the time to run the code grows in a straight line as the input gets bigger.
[X] Wrong: "Declaring var inside the loop means it runs multiple times and slows down the code a lot."
[OK] Correct: In JavaScript, var declarations are hoisted to the top of the function, so the variable is created once, not repeatedly, which means it does not add extra time per loop.
Understanding how variable hoisting works helps you explain why some code runs faster or slower, showing you know how JavaScript handles variables behind the scenes.
"What if we changed var to let inside the loop? How would the time complexity change?"
Practice
var variable declaration in JavaScript before code execution?Solution
Step 1: Understand var hoisting behavior
JavaScript movesvardeclarations to the top of their scope and initializes them asundefined.Step 2: Check initialization timing
The variable is not assigned its value until the code runs the assignment line, so before that it isundefined.Final Answer:
It is moved to the top and initialized as undefined. -> Option CQuick Check:
varhoisted = undefined [OK]
- Thinking var is not hoisted
- Assuming var is initialized with assigned value immediately
- Confusing var with let or const hoisting
Solution
Step 1: Identify hoisting behavior of let
letdeclarations are hoisted but not initialized, so accessing them before declaration causes a ReferenceError.Step 2: Check other options
varis hoisted and initialized as undefined, so no ReferenceError;constmust be initialized at declaration, soconst x;is a syntax error; function declarations are hoisted differently.Final Answer:
let x = 5;-> Option BQuick Check:
lethoisted but uninitialized causes ReferenceError [OK]
- Using const without initialization
- Confusing var and let hoisting
- Thinking function declarations behave like let
console.log(a); var a = 10; console.log(a);
Solution
Step 1: Analyze var hoisting for variable a
The declarationvar ais hoisted and initialized asundefinedbefore any code runs.Step 2: Trace console.log outputs
The firstconsole.log(a)printsundefinedbecause assignment hasn't happened yet. Aftera = 10, the secondconsole.log(a)prints10.Final Answer:
undefined 10 -> Option AQuick Check:
var hoisted as undefined, then assigned [OK]
- Expecting ReferenceError on first log
- Thinking var is assigned before declaration
- Confusing let/const behavior with var
console.log(b); let b = 20;
Solution
Step 1: Identify cause of ReferenceError
letvariables are hoisted but not initialized, so accessingbbefore declaration causes ReferenceError.Step 2: Fix by reordering code
Movingconsole.log(b)afterlet b = 20;ensuresbis declared before use, avoiding the error.Final Answer:
Moveconsole.log(b)after the declaration. -> Option DQuick Check:
Access let after declaration to avoid error [OK]
- Changing let to var without understanding scope
- Trying to initialize before declaration (syntax error)
- Assuming wrapping in function fixes hoisting
console.log(x);
if (true) {
var x = 5;
let y = 10;
console.log(y);
}
console.log(x);
console.log(y);What will be the output and why?
Solution
Step 1: Analyze var x hoisting and scope
var xis hoisted to the function or global scope and initialized asundefined. So, firstconsole.log(x)printsundefined. After assignment inside the block,xbecomes 5.Step 2: Analyze let y block scope and access
let y = 10is block scoped. Inside the block,console.log(y)prints 10. Outside the block,console.log(y)causes ReferenceError becauseyis not defined there.Step 3: Trace remaining console.logs
After the block,console.log(x)prints 5. The lastconsole.log(y)throws ReferenceError.Final Answer:
undefined 10 5 ReferenceError -> Option AQuick Check:
var hoisted globally, let block scoped [OK]
- Assuming let is accessible outside block
- Expecting var to be block scoped
- Confusing initialization timing of var and let
Ready to prove it?
Pass the test and this pattern moves unknown
