Reputation: 13
This loop breaks on the first time that it execute. Why.
<script>
for ( var i = 0; i < 10 ; i++ ) {
console.log(i);
if ( i = 5 ) {
console.log (i);
break;
}
}
</script>
output : 0 5
I'm expecting to : 0 1 2 3 4
Upvotes: 0
Views: 59
Reputation: 479
Use a double/triple comparison operator in the IF statement ==
or ===
<script>
for ( var i = 0; i < 10 ; i++ ) {
console.log(i);
if ( i == 5 ) {
console.log (i);
break;
}
}
</script>
Also, this will output 0 1 2 3 4 5 5
. If you want the output to be 0 1 2 3 4
, you should use the following code in place of the current IF
statement.
if ( i == 4 ) {
break;
}
Upvotes: 1
Reputation: 15239
You should use ===
instead of =
in the if statement
<script>
for ( var i = 0; i < 10 ; i++ ) {
console.log(i);
if ( i === 5 ) {
console.log (i);
break;
}
}
</script>
Upvotes: 0