Matija
Matija

Reputation: 533

increment in for loop javascript

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?

Upvotes: 1

Views: 31498

Answers (6)

Ashutosh Kumar
Ashutosh Kumar

Reputation: 101

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.

Upvotes: 1

VBService
VBService

Reputation: 11

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++);
}

Upvotes: 0

Aidin
Aidin

Reputation: 1290

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.

Upvotes: 2

Shafiqul Islam
Shafiqul Islam

Reputation: 5690

you can do this

<script>
var number = 0;
for (var i = 0; i < 5; i++) {
    number++;
    console.log(number);
    alert(number)
}
</script>

Upvotes: 1

Sofie Vos
Sofie Vos

Reputation: 383

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++
}

Upvotes: 1

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

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);
}

Upvotes: 11

Related Questions