Repetition

Objectives

  • Use repetition in JavaScript
  • Explain difference between using loop counters and sentinel values
  • Explain what an infinite loop is
  • Use a break statement to exit a loop
  • Use a continue statement to skip remaining code in an iteration
  • Use a for loop with a loop counter
  • Use a for loop to iterate through a collection
  • Use a do/while loop
  • Use a while loop

Repetition, document.write()

Repetition structures

Example repetition structures

break and continue

  • break lets you immediately exit a loop
  • continue skips the remaining statements in a loop and starts the next iteration
  • you have to be careful when using continue in a while or do/while loop since you might be skipping your loop counter modification statement which is usually the last statement in the loop
  • continue works well with for loops
  • break and continue demo

labeled break and continue

  • labeled break jumps to the end of the labeled statement
  • continue terminates the current iteration of the labeled loop and starts the next iteration
  • you have to be careful when using continue in a while or do/while loop since you might be skipping a loop counter modification statement which is usually the last statement in the loop
  • continue works very well with for loops
  • labeled break and continue demo

void operator

  • void evaluates the operand that follows, throws away the value, and returns undefined
  • this may be used to generate the undefined value in older browsers
  • often used to evaluate an expression without generating a result
  • the example uses it in the JavaScript code for an href attribute to prevent the original window from being trashed when attempting to open a new window
  • void operator demo

empty statement

  • an empty statement is sometimes used to create a loop with no body
  • empty statement demo

Repetition and arrays

Generating tables using JavaScript (repetition)

Source code:

Result of preceding program