1

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?

5
  • 1
    Move the number declaration outside the for loop Commented Nov 10, 2016 at 13:20
  • Thanks,it works,but why I get in console(1,2,3,4,5),insted of (0,1,2,3,4) Commented Nov 10, 2016 at 13:22
  • Then shift number++ below the console.log Commented Nov 10, 2016 at 13:22
  • Because you increment before you console.log(). If you want the value of number at the start of the loop, log first. Commented Nov 10, 2016 at 13:23
  • 1
    You are aware you can write console.log(i);? Commented Nov 10, 2016 at 13:23

6 Answers 6

11

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);
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

1

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

1

you can do this

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

Comments

1

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

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.