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

Asked

Viewed 64 times

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 has two snippets of different code, take a code in JS where I saw that this practice was common in several snippets of code, declare a variable receiving the element of array var paciente = pacientes[i];, but I find it much more practical to put the element of array 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’t see good practice in this), or it would only be to leave the code more didactic.

2 answers

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 the let can make even more sense to use this, 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 multiple iterations, and you don’t need to declare variable, do so without that statement. If not, it gives priority to code readability and maintenance.

1


Essentially it makes no difference to have an extra variable although the statement itself may be slightly worse in some versions of some browsers. Particularly I do not create variables that are not necessary, so I would make the second code.

I know a lot of programmers create variables because they learned that way and they don’t know that it can be without the variable.

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

How about wearing it like this:

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

I put in the Github for future reference.

If I can use this for of ES6 dispels the doubt.

  • I understand, my line of thought is like yours, I don’t like to create unnecessary variables.

Browser other questions tagged

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