Reputation: 861
While reading a blog, i came across a condition, which goes into infinite loop, but i didn't understand why, if we try following code
for (a=5; a < 10; a+1){
console.log(a);
}
this runs as a infinite loop, but with the following it runs fine
for (a=5; a < 10; a++){
console.log(a);
}
what is the main difference?
Upvotes: 0
Views: 87
Reputation: 81
At the first example you are not increment the value of a for (a=5; a < 10; a+1 <--- a+1 is not how to add 1 to a value You can use a++
Upvotes: -3
Reputation: 386654
The part
for (a = 5; a < 10; a + 1) {
// ^^^^^
does not change a
You need an assignment
for (a = 5; a < 10; a = a + 1) {
// ^^^
If you use a++
then it resolves to a = a + 1
The operator ++
is an increment operator.
Upvotes: 8
Reputation: 77
a++ means a=a+1 while a+1 doesn't store the value in a which means a will still 5 forever
Upvotes: 0
Reputation: 354
The problem is the a+1 part. a+1 simply returns the value of a+1. It doesn't affect anything back to a. a++ actually returns a and then increments it.
Upvotes: 1
Reputation: 1333
it is because it says: a is 0; loop through as long as it is smaller ten; then 1 (becaus 0+1)
you need to add a++
or a = a+1
Upvotes: -1
Reputation: 1074475
a++
adds one to a
and stores the result in a
.¹
a + 1
just adds one to a
, without storing the result in a
. (E.g., so you can use the resulting value for something else: b = a + 1
.)
In the "update" (increment) part of a for
, you want to modify the loop variable. So you want a++
(or ++a
), not a + 1
.
¹ Specifically, a++
(a postfix increment) reads the value of a
, adds one to a
, and then makes a
's previous value the result of the expression. So a = 1; b = a++;
leaves us with b == 1
and a == 2
.
There's also ++a
(a prefix increment), which adds one to a
and then uses the resulting value in a
as the expression's result. So a = 1; b = ++a;
leaves us with b == 2
and a == 2
.
This is sort of indicated visually: In a++
, the a
is first, and the increment comes after, and indeed the resulting value of that is of a
before it was incremented. In ++a
, the increment comes first, then the a
, which also indicates what we get as a result.
Upvotes: 3
Reputation: 3757
The first loop is not incrementing the a variable doing a+1
, the correct is a=a+1
:
for (a=5; a < 10; a=a+1){
console.log(a);
}
Upvotes: 0