user3260355
user3260355

Reputation: 13

Loops breaks before it ended

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

Answers (4)

Greg
Greg

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

Laurent Zubiaur
Laurent Zubiaur

Reputation: 438

Use i == 5 instead of i = 5 (assignment).

Upvotes: 0

Leo
Leo

Reputation: 14820

The if evaluation is incorrect. Change it to...

if ( i == 5 )

Upvotes: 0

lvarayut
lvarayut

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

Related Questions