Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript break and continue Statements

JavaScript break and continue Statements


The break statement is used to exit a loop.

continue is used to skip one iteration of a loop.


break statement

We have seen the break statement in earlier chapters of this tutorial. It is used to exit a switch() statement.

The break statement can be used to exit a loop.

After the break statement exits the loop, execution continues with the code after the loop (if any):

Example

for

(

i

=

0

;

i

<

10

;

i

++

)

{

if

(

i

==

3

)

{

break

;

}

x

=

x

"

The number is

"

i

"


"

;

}

Try it »

Since this if statement has only one line of code, the curly braces can be omitted:

for

(

i

=

0

;

i

<

10

;

i

++

)

{

if

(

i

==

3

)

break

;

x

=

x

"

The number is

"

i

"


"

;

}


continue statement

continue statementInterrupts the current iteration of the loop and then continues with the next iteration. The following example skips directly when the value is 3:

for example

for

(

i

=

0

;

i

<=

10

;

i

++

)

{

if

(

i

==

3

)

continue

;

x

=

x

"

The number is

"

i

"


"

;

}

Try it »

while example

while

(

i

<

10

)

{

if

(

i

==

3

)

{

i

++;

//

Adding i++ avoids an infinite loop

continue

;

}

x

=

x

"

The number is

"

i

"


"

;

i

++;

}

Try it »


JavaScript Labels

As you saw in the chapter on the switch statement, JavaScript statements can be labeled.

To label a JavaScript statement, add a colon before the statement:

label

:

statements

The break and continue statements are simply statements that can exit a block of code.

Syntax:

break

labelname

;

continue

labelname

;

The continue statement (with or without a label reference) can only be used inside loops.

The break statement (without a label reference) can only be used in loops or switches.

With a label reference, the break statement can be used to exit any JavaScript block of code:

Example

cars

=

[

"

BMW

"

,

"

Volvo

"

,

"

Saab

"

,

"

Ford

"

]

;

list

:

{

document

.

write

(

cars

[

0

]

"


"

)

;

document

.

write

(

cars

[

1

]

"


"

)

;

document

.

write

(

cars

[

2

]

"


"

)

;

break

list

;

document

.

write

(

cars

[

3

]

"


"

)

;

document

.

write

(

cars

[

4

]

"


"

)

;

document

.

write

(

cars

[

5

]

"


"

)

;

}

Try it »