EnZo EnZo - 2 months ago 5
Javascript Question

Declaring variables inside or outside in a for-in loop

Having this two options:

Option A:

var index;
for (index in myObject) {
// Do something

Option B:

for (var index in myObject) {
// Do something

I don't know if in the option B the variable
it's being redeclared every time of the loop or just once.


Those two snippets of code do exactly the same thing (and that's the case in most language such as C, C++ and C# amongst others). If the variable was redeclared at every iteration, then following your logic, it would also be re-initialized, and would constantly loop over the same object. Your loop would be infinite.

On a side-note, in JavaScript, all variable declarations get pushed to the function scope; this means that you can declare variables anywhere within a function, even within nested loops, and they will only be declared once.

Link to the var documentation

Relevant SO question

Other relevant SO answer

Edit courtesy of @torazaburo:

If you want to declare a variable with a local scope (as in, a variable that will only defined in the current block such as a while or if, you can use the let statement:

let var1 = 123;

It also allows you to override variables with the same name but declared in a higher scope, such as in this example from the docs:

function letTest() {
    let x = 1;
    if (true) {
        let x = 2;  // different variable
        console.log(x);  // 2
    console.log(x);  // 1

See the full documentation (and examples) here.