Declare a variable receiving element of a vector within a for is a good practice or is it unnecessary?

3

// code 1

var pacientes = document.querySelectorAll(".paciente");

for(var i = 0; i < pacientes.length; i++){
    var paciente = pacientes[i]; //linha desnecessária
    paciente.classList.remove("invisivel");
}

// Code 2

var pacientes = document.querySelectorAll(".paciente");

for(var i = 0; i < pacientes.length; i++){
    pacientes[i].classList.remove("invisivel");
}

Above you have two different code snippets, get a code in JS where I saw that this practice was common across several snippets of code, declaring a variable receiving the array element var paciente = pacientes[i]; , however I think it's much more practical to put the array element in its position and remove it from the class: pacientes[i].classList.remove("invisivel"); , as we see in the second code.

As the code was well structured I was in doubt if this would be a good practice (if yes, why? because I can not see good practice in this), or would be just to leave the code more didactic.     

asked by anonymous 09.08.2017 / 21:11

2 answers

2
Essentially it does not make a difference to have an extra variable although the statement itself may be a bit worse on some versions of some browsers. Particularly I do not create variables that are not necessary, so I would do the second code.

I know that a lot of programmer creates variables because they learned that way and they do not know what it can be without the variable.

There is a case where creating the variable can better document the code as long as it gives a good name for it, but that is not the case.

How about using this:

for (let paciente of pacientes) {
    paciente.classList.remove("invisivel");
}

If you can use this for of ES6 ends the doubt.

    
09.08.2017 / 21:22
2

There are slight performance implications when declaring variables, but in most cases easy-to-read code is preferable. Take a look to this test , and notice how the last example is slower.

With ES6 and let it can make even more sense to use this, because so the variable is restricted to the for block:

var a, b;
for(var i = 0; i < 10; i++){
    var a = i;
    let b = i;
}

console.log(a, b); // 9, undefined 

If you have a loop with many iterations, and do not need to declare the variable, it does without this statement. If this is not the case, prioritize the ease of reading and maintaining code.

    
09.08.2017 / 21:20