Function scope in Javascript - Time & Space Complexity
We want to see how the time it takes to run code changes when we use functions and their scopes.
How does the way variables are accessed inside functions affect the work done?
Analyze the time complexity of the following code snippet.
function sumArray(arr) {
let total = 0;
for (let i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
const numbers = [1, 2, 3, 4, 5];
sumArray(numbers);
This code adds up all numbers in an array using a function with its own variable scope.
- Primary operation: The for-loop that goes through each item in the array.
- How many times: It runs once for every element in the array.
As the array gets bigger, the loop runs more times, doing more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items; double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the size of the input array.
[X] Wrong: "Because the function has its own scope, it runs faster or slower depending on scope."
[OK] Correct: The function scope controls variable access but does not change how many times the loop runs. The main time cost is from looping over the array, not from scope rules.
Understanding how function scope works with loops helps you explain how your code runs step-by-step, a skill that shows clear thinking in interviews.
"What if we changed the function to call itself recursively for each array element? How would the time complexity change?"
Practice
Solution
Step 1: Understand variable accessibility
Variables declared inside a function are private to that function and cannot be accessed outside.Step 2: Compare options with this rule
Only Variables declared inside a function are only accessible within that function. correctly states this behavior.Final Answer:
Variables declared inside a function are only accessible within that function. -> Option AQuick Check:
Function scope = variables inside function only [OK]
- Thinking variables inside functions are global
- Confusing function scope with block scope
- Assuming functions can't access outer variables
Solution
Step 1: Identify valid function-scoped declarations
Inside a function,let,const, andvardeclare variables with function or block scope.Step 2: Check syntax correctness
function x = 5;is invalid syntax.let x = 5;andconst x = 5;use block scope.if (true) { var x = 5; }declaresvarwith function scope, as it is hoisted to the function level.Final Answer:
if (true) { var x = 5; } -> Option AQuick Check:
Use const or let inside functions [OK]
- Using 'function' keyword to declare variables
- Confusing block scope with function scope
- Assuming var is block scoped
function test() {
let a = 10;
if (true) {
let a = 20;
console.log(a);
}
console.log(a);
}
test();Solution
Step 1: Understand variable shadowing inside blocks
The innerlet a = 20;creates a new variable scoped to the if-block, shadowing the outera = 10.Step 2: Trace console.log outputs
Inside the if-block,ais 20, so first log prints 20. Outside the block but inside the function,ais still 10, so second log prints 10.Final Answer:
20 10 -> Option CQuick Check:
Block scope shadows outer variable = 20 then 10 [OK]
- Assuming both logs print the same value
- Confusing block scope with function scope
- Expecting ReferenceError for inner variable
function example() {
console.log(x);
let x = 5;
}
example();Solution
Step 1: Understand temporal dead zone with let
Variables declared withletare not accessible before their declaration inside the function, causing a ReferenceError if accessed earlier.Step 2: Analyze the console.log usage
The code tries to logxbefore it is declared withlet x = 5;, causing a ReferenceError.Final Answer:
ReferenceError because x is used before declaration -> Option DQuick Check:
Accessing let before declaration = ReferenceError [OK]
- Thinking var behaves the same as let here
- Expecting undefined instead of error
- Ignoring temporal dead zone rules
function counter() {
// Your code here
}
console.log(counter());
console.log(counter());
console.log(counter());Solution
Step 1: Understand function scope and persistence
Variables declared inside the function reset each call, so to keep count, it must be stored outside or as a property.Step 2: Analyze each option
function counter() { let count = 0; count++; return count; } resets count to 0 every call, so always returns 1. function counter() { if (!counter.count) counter.count = 0; counter.count++; return counter.count; } uses a property on the function to store count, preserving it across calls. let count = 0; function counter() { count++; return count; } uses a global variable, which works but is not function scope. function counter() { const count = 0; count++; return count; } tries to increment a constant, causing error.Final Answer:
function counter() { if (!counter.count) counter.count = 0; counter.count++; return counter.count; } -> Option BQuick Check:
Use function property to store persistent count [OK]
- Resetting count inside function each call
- Using const and trying to increment
- Using global variables instead of function scope
Ready to prove it?
Pass the test and this pattern moves unknown
