JavaScript variables declare outside or inside loop?

In JavaScript, variables can be declared either inside or outside loops without performance differences. However, the choice affects variable scope and code readability.

Variable Scope: var vs let

With var, variables are function-scoped regardless of where declared. With let, variables are block-scoped, meaning they're only accessible within their block.

Example: Variable Declared Outside Loop

When declared outside, variables have broader scope and can be accessed throughout the function:

function myFunction1() {
    var i; // Function scope - can be used throughout the function
    
    for (i = 0; i < 3; i++) {
        console.log("Hello " + i);
    }
    
    console.log("Final value of i: " + i); // Accessible after loop
}
myFunction1();
Hello 0
Hello 1
Hello 2
Final value of i: 3

Example: Variable Declared Inside Loop

When declared inside, variables are limited to the loop's scope:

function myFunction2() {
    for (var j = 0; j < 2; j++) { // 'j' is only defined inside the loop
        console.log("Welcome " + j);
    }
    
    console.log("j after loop: " + j); // Still accessible with var
}
myFunction2();
Welcome 0
Welcome 1
j after loop: 2

Block Scope with let

Using let provides true block scoping:

function testBlockScope() {
    for (let k = 0; k < 2; k++) {
        console.log("Inside loop: " + k);
    }
    
    try {
        console.log("Outside loop: " + k); // This will throw an error
    } catch (error) {
        console.log("Error: " + error.message);
    }
}
testBlockScope();
Inside loop: 0
Inside loop: 1
Error: k is not defined

Practical Example: Array Processing

function processArray() {
    var multiplier = 12;
    var array = [12, 34, 56, 6];
    
    for (let i = 0; i < array.length; i++) {
        console.log(array[i] * multiplier);
    }
}
processArray();
144
408
672
72

Best Practices

Declaration Location Use Case Recommended Keyword
Outside Loop Variable needed after loop let or var
Inside Loop Variable only used in loop let (preferred)

Conclusion

Use let inside loops for better scoping and declare variables where they're needed for improved readability. This approach prevents accidental variable reuse and makes code more maintainable.

Updated on: 2026-03-15T20:02:46+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements