JS For In LoopFor 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;...
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:
One way to putforloops in good use would be to optimize them, by removing the expressions.Each one of them can be omitted, or you can even omit them all. We will be using the same code of the example above, only we’ll modify it according to the thing we want to show you, so ...
log(counter + ' - Inside for loop on TechOnTheNet.com'); } console.log(counter + ' - Done for loop on TechOnTheNet.com'); In this for loop example, the loop will continue as long as counter is less than 5 as specified by: counter < 5; The for loop will continue while ...
From the example above, you can read:Statement 1 sets a variable before the loop starts (var i = 0).Statement 2 defines the condition for the loop to run (i must be less than 5).Statement 3 increases a value (i++) each time the code block in the loop has been executed....
Here is an example:const user = { name: 'John Doe', email: 'john.doe@example.com', age: 25, admin: false } for (const key in user) { console.log(key) // property name console.log(user[key]) // property value } for...in loop examples...
"array value: 1" "array value: 2" "array value: 3" "array value: a" "a is string at index: 3,loop stoped using return" We’ve achieved the same result as the first example by using the return keyword. We have placed that for loop code in the function’s body and used the ...
Example 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 ...
In the next example, we’ll create an empty array and populate it with the loop counter variable. modifyArray.js // Initialize empty arrayletarrayExample=[];// Initialize loop to run 3 timesfor(leti=0;i<3;i++){// Update array with variable valuearrayExample.push(i);console.log(array...
Iterating over an Array using the for…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...