+ 3

Is it good define a variable inside a loop?

Someone mentioned to me that define a variable inside the loop is bad because the variable is defined multiple times and it could affect the memory. Is it true?

16th May 2017, 12:08 AM
Jorge Daniel Lopez Irusta
Jorge Daniel Lopez Irusta - avatar
3 Answers
+ 6
Not really. The real difference for other languages is that defining the variable outside the loop makes it a local variable, increasing the lifetime of the variable. (Note* I'm Referring to the loop Itteration here) This could I suppose increase memory usage. But javascripts var doesn't have block scope, so I don't think any of that matters. Although, from what I've read you should still declare the variables you will use in the loop outside. The reason is actually because with the other languages like C that have block scope, it would be better to define the variable outside like that person said. So it's better to follow them to avoid confusion encase a programmer is used to those languages. http://javascript.crockford.com/code.html#variable%20declarations Edit: Allow me to further elaborate what I said encase I didn't hit the point. Because the var doesn't have block scope you are only declaring the variable once in the loop. It is NOT being created over and over even if declared inside the loop. So it doesn't matter if you declare it inside or outside. This is different for most other languages. So, you should stick to there programming standards anyway and declare it outside to avoid confusion from different backgrounds.
16th May 2017, 12:27 AM
Rrestoring faith
Rrestoring faith - avatar
+ 1
If you're talkin' about JS: for (var i=0;i<5;i++){} It will be declared only once. But for sure if you're using loop inside loop -> you can make global variable.... But ...but...realy...loop inside loop...and too much global variables for nothin' ... or declare variable many times - all of this things aren't good. For sure you can check each time if it's declared and reset each time(also it can be cause of some errors)...and then it will increase your code size.... Shitty solution too.... Just...forget about . Here's nothin' to realy care.
16th May 2017, 2:28 AM
Rose Sevenyears
Rose  Sevenyears - avatar
0
@Rrestoring That's a good shot.
16th May 2017, 12:40 AM
Vishnu ks
Vishnu ks - avatar