Mastering the JavaScript For Loop: A Comprehensive Guide
Table of Content:
JavaScript For Loop
JavaScript For Loop is used to execute a block of code for a number of times based on a condition.
In this tutorial, we will learn how to define/write a JavaScript For loop, and its usage using example programs.
Syntax
The syntax of JavaScript For Loop is
for (initialization; condition; update) { //statements }
where
- initialization can contain one or more variables defined and initialized.
- condition is the expression which is checked before executing the statements inside for loop.
- update can contain increment, decrement, or any update to the variables. Variables defined in the initialization part can be updated here. update section is executed after executing the statements inside for loop.
Please note that all the three: initialisation, condition, and update are optional in a for loop statement.
Examples
In the following example, we execute a block of code that appends ‘hello world’ to a pre block HTML element ten times using a For Loop.
Output:
If you will run above code, you will get below output.
We can also use a for loop to iterate over the elements of an array, using array length in condition, as shown in the following example.
Output:
If you will run above code, you will get below output.