The do...while statement

The do...while statement is similar to while it although guarantees an iteration before the check is carried out. Its syntax is formed of the do keyword followed by its body and then a typical parenthesized while expression:

do IterationBody while (ConditionExpression)

The purpose of each part is as follows: 

  • IterationBody can be either a single-line or block statement and will be run once initially and then as many times as ConditionExpression evaluates to true.
  • ConditionExpression is evaluated to determine whether IterationBody should run more than once. If it evaluates to true, then the Body portion will run. ConditionExpression will then be re-evaluated and so on. The cycle only stops when ConditionExpression evaluates to false.

Although the behavior of the do...while statement is different from  regular while statement, its semantics and broad applications remain the same. It is most useful in contexts where you need to always complete at least one step of an iteration before either checking whether to continue or changing the subject of the iteration. An example of this would be upward DOM traversal. If you have a DOM element and wish to run certain code on it and each of its DOM ancestors, then you may wish to use a do...while statement as follows:

do {
// Do something with `element`
} while (element = element.parentNode);

A loop like this will execute its body once for the element value, whatever element is, and then will evaluate the assignment expression, element = element.parentNode. This assignment expression will evaluate to its newly assigned value, meaning that, in the case of element.parentNode being falsy (for example, null) the do...while will halt its iteration.

Assigning values in the ConditionExpression portion of a while or do...while statement is relatively common although it can be obscure to fellow programmers, so it's best to only do so if it's plainly obvious what the intent of the code is. If the preceding code was wrapped in a function called traverseDOMAncestors, then that would provide a helpful clue.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.62.94