Answer the question
In order to leave comments, you need to log in
JavaScript code style. Should I use variable declarations inside a loop?
Good afternoon, dear JavaScript gurus. Help, please, with a question on an admissibility of the declaration of variables in a cycle. In books of authoritative authors, it is usually recommended to declare all variables inside a function inside a single var block, something in style var url, price, i, j;
, while on well-known resources, for example, javascript.ru in examples often use options
Are there any standards in terms of industrial coding, about which preferred option? for (var i=0;i<10; i++) {}
Answer the question
In order to leave comments, you need to log in
Of course, it seems that putting the variable i at the beginning of the function is stupid. But as soon as you give it a meaningful name (itemIndex, for example, or something more specific) and break the code into small functions, all prejudices disappear.
es6 has a cool thing let, so it should be used to declare variables in a loop, it's better than var and you don't need to bother with closures.
if we talk about es5, then yes, for a cycle it is better to declare a variable inside the cycle, and not before or outside the function. Well, besides, this is the most common and convenient style.
for (var i = 0; i < 10; i++) { }
In this case, the variable is var i
declared not in the body of the loop, but in its condition - at least there is no urgent need for micro-optimization here.
And regarding the style, we can say that this option is the most readable.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question