Explanation of how loop variable declaration For/In works

Asked

Viewed 59 times

0

var meusDados = {
    nome: 'Bruno Coelho',
    email: '[email protected]',
    idade: 23
};
var dados;
for(dados in meusDados){
    console.log(meusDados[dados]);
}

Why declaring the variable given before the for/in is required?

  • Use for(let dados... because it is always better to avoid global scope. But the let may not be supported in older browsers.

2 answers

3


Because if you don’t declare, where will you store the content during the loop? The variable needs to exist to receive the value. But it doesn’t have to be necessarily before the loop; it can be inside it too, which I find particularly readable.

var meusDados = {
    nome: 'Bruno Coelho',
    email: '[email protected]',
    idade: 23
};

for(var dados in meusDados){
    console.log(meusDados[dados]);
}

// Perceba que dados continua existindo fora do laço
console.log(dados);

I put a console.log at the end showing that the variable dados continues to exist even outside the loop. Depending on your taste, you may find that this pollutes the overall scope, as a variable that is used in only one specific location continues to exist outside of it. If so and you wish to avoid such an occurrence, you can use the let:

const meusDados = {
    nome: 'Bruno Coelho',
    email: '[email protected]',
    idade: 23
};

for(let dados in meusDados){
    console.log(meusDados[dados]);
}

// Perceba que dados NÃO continua existindo fora do laço
console.log(dados);

What is the difference between variable declaration using Let and var?

2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.