Loops
Loops are used in JavaScript to perform repeated tasks based on a condition. Conditions typically return true
or false
. A loop will continue running until the defined condition returns false
.
while
loop
while
loopThe most fundamental repetition construct, present in pretty much every programming language, is the while
loop. The condition is evaluated before executing the statement. The loop is run for as long as the condition is true
.
Syntax
Example
Print all numbers up to 20.
do...while
loop
do...while
loopThe condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
Syntax
Example
Print all numbers up to 20.
for
loop
for
loopThe for
statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement to be executed in the loop.
Syntax
The for
loop consists of three optional expressions, followed by a code block:
initialization
- This expression runs before the execution of the first loop, and is usually used to create a counter.condition
- This expression is checked each time before the loop runs. If it evaluates totrue
, thestatement
or code in the loop is executed. If it evaluates tofalse
, the loop stops. And if this expression is omitted, it automatically evaluates totrue
.finalExpression
- This expression is executed after each iteration of the loop. This is usually used to increment a counter, but can be used to decrement a counter instead.
Any of these three expressions or the the code in the code block can be omitted.
Example
Print all numbers up to 20.
continue
statement
continue
statement The continue
statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
Example
Using continue
print only even numbers
break
statement
break
statement The break
statement terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
Example
Using break
exit the while loop after 100.
References
Last updated
Was this helpful?