In JavaScript, the for loop is used for iterating over a block of code a certain number of times or over the elements of an array. In this tutorial, you will learn about the JavaScript for loop with the help of examples.
For loop example: 1 2 3 4 5 6 var sum = 0; for (var i=1; i<=100; i++) { sum += i; } alert(sum); //5050 You may use break to jump out of the loop:1 2 3 4 5 6 7 var sum = 0; for (var i=1; i<=100; i++) { if (i == 50) break; stop the loop...
You’ll see in the examples how each of these clauses is translated into code. So let’s start right away. Using simpleforloops The most typical way to useforloops is counting. You just need to tell the loop where to start, where to finish, and with what pace to count. This is ho...
You’ll see in the examples how each of these clauses is translated into code. So let’s start right away. Using simpleforloops The most typical way to useforloops is counting. You just need to tell the loop where to start, where to finish, and with what pace to count. This is ho...
Introduction to loops What is the for loop meant for Syntax of for Basic for loop examples Nested for loops The break and continue keywords The return keyword Introduction Loops, also known as loop statements or iteration statements, are amongst those ideas in programming without which it's not...
This JavaScript tutorial explains how to use the for loop with syntax and examples. In JavaScript, the for loop is a basic control statement that allows you to execute code repeatedly for a fixed number of times.
// Declare variable outside the loopleti=0;// Omit all statementsfor(;;){if(i>3){break;}console.log(i);i++;} Copy Output 0 1 2 3 As we can see from the above examples, including all three statements generally produces the most concise and readable code. However, it’s useful to...
For example, let i = 0; // false condition // body executes once do { console.log(i); } while (i > 1); // Output: 0 Run Code On the other hand, the while loop doesn't execute its body if the loop condition is false. For example, let i = 0; // false condition // ...
for (let i = 0; i < 5; i++) { text += "The number is " + i + ""; } Try it Yourself » From the example above, you can read:Expression 1 sets a variable before the loop starts (let i = 0).Expression 2 defines the condition for the loop to run (i must be less ...
We’ll look at how for...in loop statements are used in JavaScript, the syntax, examples of how it works, when to use or avoid it, and what other types of loops we can use instead. Key Takeaways The for loop in JavaScript is used to iterate through items in a collection such as ...