I don't know why but I can't increment value in for loop normally.
for (var i = 0; i < 5; i++) {
var number= 0
number++
console.log(number);
}
That's the simple example,and I get 5 times number 1 in console,insted of 0,1,2,3,4. How I can make that work?
6 Answers 6
You're declaring the variable inside the loop, so it happens every time the loop runs. Simply move the declaration outside...
var number = 0;
for (var i = 0; i < 5; i++) {
number++;
console.log(number);
}
Comments
It prints 1, 1, 1, 1, 1 because you reset numberin every iteration.
change your code to:
for (var i = 0; i < 5; i++) {
console.log(i);
}
or
var number = 0;
for (var i = 0; i < 5; i++) {
console.log(number);
number++;
}
(Answer to additional question in comments) You get 1,2,3,4,5 because you increment number before you print it.
Comments
You keep resetting the value of number to 0. Try setting it before the loop:
var number= 0
for (var i = 0; i < 5; i++) {
console.log(number);
number++
}
Comments
you can do this
<script>
var number = 0;
for (var i = 0; i < 5; i++) {
number++;
console.log(number);
alert(number)
}
</script>
Comments
The issue with your code is that you're declaring the number variable inside the for loop, so it gets reinitialized to 0 with each iteration. To fix this, you should declare the number variable outside the loop, before it starts. Here's the corrected code:
for (var i = 0; i < 5; i++) {
number++;
console.log(number);
With this change, the number variable will retain its value across iterations, and you'll see the expected output of 0, 1, 2, 3, 4 in the console.
Comments
If you just want to iterate in range from 0 to 5, you can use "i" variable.
for (let i=0; i<5; i++) {
console.log(i);
}
but if you need use for some reason another variable as you name it "number", in javascript you can write too as belowe
let number = 0;
for (let i=0; i<5; i++) {
console.log(number++);
}
or
for (let i=0, number=0; i<5; i++) {
console.log(number++);
}
number++below theconsole.logconsole.log(). If you want the value ofnumberat the start of the loop,logfirst.console.log(i);?