V
V
Vetal Matitskiy2015-09-23 07:32:46
JavaScript
Vetal Matitskiy, 2015-09-23 07:32:46

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

4 answer(s)
A
Alexey Ukolov, 2015-09-23
@alexey-m-ukolov

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.

S
Sarkis Arutiunian, 2015-09-23
@sarkis-tlt

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.

A
Andrey Danilov, 2015-09-23
@Danand

for (var i = 0; i < 10; i++) { }
In this case, the variable is var ideclared 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 question

Ask a Question

731 491 924 answers to any question