Simple question about console.log in used with the For loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Simple question about console.log in used with the For loop

Hello. I have a question about console.log used in a For loop. Does console.log print the value of the first statement at the start of each loop? Consider the following: https://code.sololearn.com/W9m6a3s2CvtX/#js After the first For (i;i<l;i++) happens, i should increase by 1. However, console.log returns the value as 0. So I can only think that console.log is returning the value at the start of the iteration. How can I make it so it returns the increased value? EDIT: I achived this by using document.write(text + i + "<br>"); EDIT AGAIN: My code just got more complicated. I used IF for displaying the final value, but outside the code block. However, if I used IF inside the block, it console.log will only return the first loop. I just wanted to know whether there is a way to get the last value by with some code inside the loop.

9th Jul 2019, 5:20 PM
jesus Aguilera
jesus Aguilera - avatar
3 Answers
+ 1
Add let in front of i and l. It is used to declare variables.
9th Jul 2019, 5:26 PM
Drax
Drax - avatar
+ 1
Also, please note that you should avoid var, as it is scoped to the function and can lead to non desired behavior. You could also use const in front of l, as its value is not meant to change.
9th Jul 2019, 5:27 PM
Drax
Drax - avatar
0
Oh, thanks for that! Nice to know. Also, I still would like to confirm my question about why at the start of each loop console.log prints the initial value of the first variable.
9th Jul 2019, 7:35 PM
jesus Aguilera
jesus Aguilera - avatar