+ 2

Loops variables declaration

Does declaring variables of a loop (such as i, j) out side the loop itself affect how loops work by any means (specially when looping through nested arrays "arrays inside an array" ) caused I faced a challenge that somehow my code didn't work until I declared my loop variables inside the for() brackets ?!! 🤷

18th Apr 2020, 6:23 PM
Ali Kh
Ali Kh - avatar
4 ответов
+ 2
Are you resetting the inner loop variable back to the original definition once the inner loop is done iterating? https://code.sololearn.com/WHPluES92XWY/#html https://www.w3schools.com/js/js_loop_for.asp
18th Apr 2020, 9:19 PM
ODLNT
ODLNT - avatar
+ 1
ODLNT now I get it, thank you a lot
18th Apr 2020, 10:36 PM
Ali Kh
Ali Kh - avatar
0
It depends how you declare it. If you declare the variable with let in the for-line, it won't be available anymore after the loop ended. If you define it with var, it's the same as if you had declared it before the loop - it will be available outside and in the loop.
18th Apr 2020, 6:39 PM
HonFu
HonFu - avatar
0
@HongFu I declared it firstly with var at the top of my code .. but it didn't work, (I think it worked only on the 1st subarray but neglected the others) then when I changed that to declaring it inside the for () brackets it worked https://edabit.com/challenge/ve7mQnJsjtFep97fm Here's a link of the challenge try to do it with declaring before using loops and it won't work (I know the challenge could be solved with high order functions 😅 but it's what it's)
18th Apr 2020, 6:43 PM
Ali Kh
Ali Kh - avatar