Using JavaScript for Loop
As in all C-based programming languages, you can handle your continuous commands under a for loop. This structure is used in the same way in JavaScript. Apart from the for loop, there are also the following loops in the JavaScript language.
for – Used to execute a certain number of commands between blocks.
for/in – used to read properties of arrays or objects (same as foreach in other languages)
while – code between blocks is executed as long as the condition is true.
do/while – code between blocks is executed as long as the condition is true, at least once.
Spelling Rule:
for (expr1; expr2; expr3) {
code block to be executed
}
expression1: Defining the starting variable before the loop starts (eg: i=0)
expression2: Shows the loop operating condition. (Ex: i<=100)
expression3: Change (increase/decrease) of the initial variable (Ex: i++)
Example 1: 0-100.
for(var i=0;i<=100;i++){
document.write("Number"+i);
}
Example 2: You can use loops and conditions together. Make a program that prints even numbers between 0-100.
Explanation: If the remainder from dividing the number i by 2 is 0 (i%2< /span>==0) number is even.
for(var i=0;i<=100;i++){
if(i%2==0)
{
document.write("Number"+i);
}
}
Example 3: You can print array elements to the screen. To find out the number of elements in the array, we can find out the number of elements in the array with the array.length property. In the example below, an array named days is defined. The number of the array is learned with the days.length property, and each element of the array is printed to the screen with days[i] in the loop.
var days=["MONDAY","TUESDAY"," WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"];
for(var i=0;idocument.write("Number"+< /span> days[i] +"
");
}
Example 4: Write a javascript example that takes the entered message and the number of repetitions from the user and prints them on the screen.
var message = prompt(>"Enter Message to Print");
var number = prompt("Enter Number of Loops");
for (var i = 0; i < parseInt(number); i++) {
document.write(message + "
");
}