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...
which means that it takes the command right after the loop, without executing the rest of it, but instead doing whatever code is next. Here’s an example of how you can use it:
for...in loop and prototypesObjects in JavaScript can have properties inherited from object prototypes.For example, objects created using Array and Object constructors inherit many properties from Object.prototype and String.prototype. The for...in statement iterates over own properties of the object...
Theforstatement in JavaScript has the samesyntaxas in Java and C. It has three parts: Initialization- Initializes the iterator variablei. In this example, we initializeito 0. Condition- As long as the condition is met, the loop continues to execute. In this example, we check thatiis less...
In JavaScript, the for loop is used for iterating over a block of code a certain number of times, or to iterate over the elements of an array. Here's a quick example of the for loop. You can read the rest of the tutorial for more details. Example for (let i = 0; i < 3; i...
The syntax for the for loop in JavaScript is: for(initialize;test;increment){// statements} Parameters or Arguments initialize The declaration of the counter variable and assigning its initial value. For example, to initialize a variable called counter and set its value to 1, you could usevar...
For loop example over an iterable object In the following example, we’re looping over the variable obj and logging each property and value: const obj = { "a": "JavaScript", 1: "PHP", "b": "Python", 2: "Java" }; for (let key in obj) { console.log(key + ": " + obj[key...
of Loop in JavaScript One of the best usages of JavaScript’s for…of loop is to iterate over an array. It makes iterating through an array incredibly straightforward. For this example, we start by creating a constant (const) variable called “fruits“. Within this variable, we will store...
Usingletin a loop: Example leti =5; for(leti =0; i <10; i++) { // some code } // Here i is 5 Try it Yourself » In the first example, usingvar, the variable declared in the loop redeclares the variable outside the loop. ...
JavaScript For Loop ExampleThis example will show you how to create a simple for loop that prints out the value of our counter until the counter reaches 5. Pay special close attention to the three different items that are on the first line of the for loop code. These are the important ...