Introduction to Loops in JavaScript: Iteration and Examples
☰Fullscreen
Table of Content:
Loops provide a quick and effortless way to repeat certain operations. Let us see some of the important loops in JS
- for statement
- while statement
- do...while statement
- For of loop
- For in Loop
- Initialization - An expression to initialize counter variable
- condition - An expression to evaluate every loop iteration
- final-expression - An expression to update the counter variable
- Write a program to draw a chessboard of size 8X8.
- Each line of the chessboard should have
a +
anda -
.+
indicates black cell and-
indicates a white cell on the chess board. - Draw a border with * on all four sides.
- You can try this using different loops.
For Loop
Syntax
for ([initialization]; [condition]; [final-expression]) statement
Example:
for (var i = 0; i < 9; i++) { console.log(i); // more statements }
While Loop
Syntax
while (condition) { statement}
Example:
var n = 0; var x = 0; while (n < 3) { n++; x += n; }
Do... While Loop
Syntax
do statement while condition
Example:
var i = 0; do { i += 1; console.log(i); } while (i<5);