Programming
Variable Declaration
Loop Structures
Code Optimization
Programming Best Practices

Declaring variables inside or outside of a loop

Codemia Knowledge Hub ·

Declare a variable inside the loop when it is only needed for one iteration: it stays scoped to the loop, resets each time, and cannot leak side effects. Declare it outside when its value accumulates across iterations or is needed after the loop ends. In most high-level code the performance difference is negligible; it matters mainly in system-level or performance-critical code.

Declaring variables inside a loop

A variable declared inside a loop is recreated on each iteration and is local to the loop, so nothing outside can access it. That helps prevent unwanted side effects and keeps code cleaner.

Example in JavaScript:

javascript
1for (let i = 0; i < 10; i++) {
2    let localVariable = i * 2;
3    console.log(localVariable);
4}

localVariable is created anew on every iteration and is not accessible outside the for loop.

Because the variable is re-declared each time, there can be a slight performance cost, especially when the loop runs many times or creating the variable is resource-intensive.

Declaring variables outside a loop

Declare outside when the same variable is used in every iteration or its value is needed after the loop. This also avoids the overhead of repeated declarations.

Example in Python:

python
1sum = 0
2for i in range(10):
3    sum += i
4print(sum)

sum accumulates values across the loop, and its final value is used afterwards. This can help performance in languages where memory allocation and garbage collection are costly.

When placement affects performance: C example

Placement can matter more in high-load scenarios or lower-level languages such as C and C++, where memory management and processor time are critical.

c
1#include <stdio.h>
2
3int main() {
4    int i;
5    int outsideLoop = 0;
6    for(i = 0; i < 1000000; i++) {
7        outsideLoop += i;
8    }
9
10    for(i = 0; i < 1000000; i++) {
11        int insideLoop = 0;
12        insideLoop += i;
13    }
14
15    return 0;
16}

Here, declaring insideLoop inside the loop could be less efficient than outsideLoop, because memory has to be allocated and released on each pass.

Inside vs outside at a glance

ScenarioInside LoopOutside Loop
ScopeLimited to inside the loopAvailable both inside and outside of the loop
PerformanceSlower in high-load or language-specific cases due to repeated allocationsOften faster due to single allocation
Use CaseWhen variable shouldn’t exist outside the loop or must reset each timeWhen value builds over iterations or is needed after loop execution

For most code, choose based on scope: keeping variables inside the loop prevents bugs and makes code easier to follow. In performance-critical code, avoiding unnecessary allocations by declaring outside the loop can save time and resources.


Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms