1/21/2014

Loops and switch | JavaScript Tutorial
Log in

JavaScript Tutorial
Home » Tutorial » JavaScript: from the Ground to Closures » First Steps » Operators and constructs
‹ Comparison operators, if..else Functions: declarations and expressions › Tutorial

JavaScript: from the Ground to Closures
JavaScript: from the Ground to Closures Javascript and related technologies First Steps
First Steps

Loops and switch
Ilya Kantor

1. The w h i l eand d o . . w h i l eloops 2. The f o rloop 3. Jumping out with b r e a k 4. Skipping with c o n t i n u e 5. Jumping over blocks with labels 6. The s w i t c hconstruct 1. Example 2. User-input example Loop constructs allow to repeat a block of code multiple times, while the given condition is true. JavaScript has three types of loops.

Like

0

Setup your environment Hello, World! Variables and statements Browser Developer's Tools User interaction: alert, prompt and confirm Operators and constructs
Operators and constructs Operators Comparison operators, if..else Loops and sw itch

The w h i l eand d o . . w h i l eloops
These loops check condition before/after every iteration: 1 2 3 4 5 6 7 w h i l e ( i < 1 0 ){ / /d os o m e t h i n g } d o{ / /s o m e t h i n g }w h i l e( i < 1 0 )

Functions: declarations and expressions Mastering data types Four scents of "this" Type detection Function arguments Static variables and methods Scopes and Closures Decorators

Document and Events Object Oriented Programming Timing Frames and windows Regular expressions in JavaScript Advanced and Extra stuff

The code inside curly braces will repeat while the condition (i < 1 0in the example) holds true. An endless loop looks like: w h i l e ( t r u e ){ / /d os o m e t h i n g } As with many other languages, you check for 0like this:
Run!

1 v a ri=3 2 w h i l e ( i ){ 3 a l e r t ( i ) 4 } The loop above will stop when i = = 0 , because 0is f a l s ein boolean context. Note that i -decrements i , but returns a value before decrement. That’s why alert starts with 3and ends with 1 .

Donate Donate to this project

The f o rloop
This loop looks like: f o r ( i = 0 ; i < 1 0 ; i + + ){ a l e r t ( i ) } The statement consists of three parts divided by semicolon and the body. Here is a description of the parts (generally same as in C, Java, PHP etc): i = 0- starter This executes at loop start. i < 1 0- loop condition The condition to check if loop is finished. It is checked after every execution of loop body. i + +- increment An action to perform after every iteration, but before the loop condition is checked. For the given example, the loop body is executed with istarting from 0to 9 . When i + +makes i = 1 0 , the loop is stopped by condition i < 1 0 .

http://javascript.info/tutorial/loops-and-switch

1/5

.} Loops and switch | JavaScript Tutorial You can leave any part of f o rempty. http://javascript. When a user types in a number>100. They are used to break/continue through several nested loops. This is what b r e a kstatement does. The task is to rewrite f o rloop into w h i l ewith same code behavior. . . Open solution Create a loop that keeps prompting for a number exceeding 100. and can be put on a separate line: 1 o u t e r : 2 f o r ( . The execution will continue from right after the loop (marked with asterisk). 4 i n n e r :f o r ( .1/21/2014 It is a common practice to define a loop variable inside f o r : f o r ( v a ri = 0 . Jumping over blocks with labels Loop labels is something special in JavaScript. . 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0 v a ri = 0 w h i l e ( t r u e ){ i + + / /i n c r e a s eib yo n e i f( i > 5 )b r e a k a l e r t ( i ) } / /( * ) Skipping with c o n t i n u e The c o n t i n u eoperator allows to skip the rest of the block. Pressing “ESC” or clicking “Cancel” must stop the loop also. ){ 3 / /. The following loop will exit from loop when ibecomes 6 . . For example. ){ / /w i l lr e p e a te t e r n a l l y( i nt h e o r y ) } Check out the page: tutorial/intro/source/loop. . the following code ignores negative values: Run! 1 v a ri=3 2 w h i l e ( i < 3 ){ 3 4 i + + 5 6 i f( i < 0 )c o n t i n u e 7 8 a l e r t ( i ) / /( * ) 9 } The code labelled with asterisk is never executed for negative i . the loops must stop.html .info/tutorial/loops-and-switch 2/5 . a simple infinite loop looks like: f o r ( . For example. Check how it should work here . thanks to c o n t i n u e .i < 1 0 . . ){ 5 / /. Open solution Jumping out with b r e a k Sometimes it is required to break out of the loop right now.i + + ){. . . A label is put before loop statement.

i + + ){ 0 5 i f( i > 4 )b r e a km y . . to the end of the block labelled with m y . . In the given example.1/21/2014 6 } 7 } Loops and switch | JavaScript Tutorial One can use b r e a kl a b e land c o n t i n u el a b e lto jump through several loops. any other value in place of 10. If no case matches. You can use c o n t i n u ein exactly the same way.i < 1 0 .i + + ){ i f( i>3 )b r e a ko u t e r . 1 0 1 1 } 1 2 a l e r t ( " a f t e rm y " ) . 4 c a s e' v a l u e 2 ' : / /i f( x= = =' v a l u e 2 ' ) 5 . Even in latest editions of the standard. http://javascript. and you also can’t break to a place of code before. 1000. .info/tutorial/loops-and-switch 3/5 . Open hint 1 Open solution The s w i t c hconstruct Another useful construct in JavaScript is s w i t c h . n 1all divide nwith a non-zero remainder. It will jump to next iteration of labelled loop. b r e a kjumps over s o m e _ c o d e . . Run! 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0 1 1 1 2 1 3 1 4 o u t e r : f o r ( . } / /t h ep a r to fc o d ea f t e ri n n e rl o o pi sn e v e re x e c u t e d . ){ f o r ( i = 0 .7. An interesting thing about labels is that you can attach them to blocks: Run! 0 1 m y :{ 0 2 0 3 f o r ( . n > 1is prime if numbers 2 . JavaScript has no goto. Or. . because you can’t break outside loops. The code should also work if 100. It provides a short syntax for multiple equality tests. A number is prime if it has exactly two divisors: 1 and itself. but it is not. it goes to optional default label.S.3. 0 6 } 0 7 } 0 8 0 9 s o m e _ c o d e .i < 1 0 . P. Create a code which outputs all primes less than 10. ){ 0 4 f o r ( i = 0 . That looks like g o t o . 6 d e f a u l t : 7 / /d e f a u l tc o d e 8 } Switch operator checks the argument against each c a s eand executes the code below the match until it meets the b r e a koperator. There should be 2. . It looks like this: 1 s w i t c h ( x ){ 2 c a s e' v a l u e 1 ' : / /i f( x= = =' v a l u e 1 ' ) 3 .5. The following example demonstrates how to break through two loop levels. / /b e c a u s eb r e a kj u m p sr i g h tt oo u t e rl a b e l } a l e r t ( " i = " + i ) . Example Let’s see a working example. . in other words.

info/tutorial/loops-and-switch 4/5 . skipping first alert. if.s w i t c hgoes right to c a s e2 . every c a s eis appended by b r e a k . but prompt returns either a string or n u l l . User-input example The next example is based on user-input.. © Ilya Kantor. we need to add b r e a k : Run! 0 1 v a rx=2 0 2 0 3 s w i t c h ( x ){ 0 4 c a s e1 : 0 5 a l e r t ( ' n e v e re x e c u t e s ' ) 0 6 b r e a k 0 7 0 8 c a s e2 : 0 9 a l e r t ( ' x= = =2 ' ) / /< -s t a r t 1 0 b r e a k / /s t o p ! 1 1 1 2 c a s e3 : 1 3 a l e r t ( ' x= = =3 ' ) 1 4 b r e a k 1 5 } In the example above.1/21/2014 Run! Loops and switch | JavaScript Tutorial 0 1 v a rx=2 0 2 0 3 s w i t c h ( x ){ 0 4 c a s e1 : 0 5 a l e r t ( ' n e v e re x e c u t e s ' ) 0 6 0 7 c a s e2 : 0 8 a l e r t ( ' x= = =2 ' ) 0 9 1 0 c a s e3 : 1 1 a l e r t ( ' x= = =3 ' ) 1 2 } The example above outputs 2 and 3. then the second one and stops at b r e a k . If you type in 3 . "JavaScript™ is a registered trademark of Oracle corp. That’s also the reason why c a s ef a l s ealso never works in this example. not number. so c a s e 3will not match.s w i t c hgoes to default case. 2011. If you enter 2 . This site is not affiliated with Oracle corp. http://javascript. That’s because it starts execution from c a s e 2and goes on. Run! 0 1 v a ra r g=p r o m p t ( " E n t e ra r g ? " ) 0 2 s w i t c h ( a r g ){ 0 3 c a s e' 0 ' : 0 4 c a s e' 1 ' : 0 5 a l e r t ( ' O n eo rz e r o ' ) 0 6 0 7 c a s e' 2 ' : 0 8 a l e r t ( ' T w o ' ) 0 9 b r e a k 1 0 1 1 c a s e3 : 1 2 a l e r t ( ' N e v e rh a p p e n s ' ) 1 3 1 4 c a s ef a l s e : 1 5 a l e r t ( ' F a l s e ' ) 1 6 b r e a k 1 7 1 8 d e f a u l t : 1 9 a l e r t ( ' U n k n o w nv a l u e :' + a r g ) 2 0 } If you enter 0or 1it starts execution from the corresponding c a s e . That’s because p r o m p treturns string ' 3 ' . executes the first alert. ‹ Comparison operators.else Functions: declarations and expressions › The content of this site is available under the terms of CC BY-NC-SA. To stop the execution of a case. It would work if a r g= = =f a l s e . That is a usual practice to ensure that only one case is executed. Switch uses = = =to check equality.

1/21/2014 Loops and switch | JavaScript Tutorial http://javascript.info/tutorial/loops-and-switch 5/5 .