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...
Removingforloop’s clauses 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 w...
Removingforloop’s clauses 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 w...
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...
For example: for (var counter = 1; counter < 5; counter++) { console.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...
for(leti =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 than 5). ...
Example: JavaScript for...in Loop constsalaries = {Jack:24000,Paul:34000,Monica:55000}; // use for...in to loop through// properties of salariesfor(letiinsalaries) {// access object key using [ ]// add a $ symbol before the keyletsalary ="$"+ salaries[i];// display the valuesco...
for ([initialization]; [condition]; [update]) statement; Notice the [ ] around each of the three configuration segments — this signifies that each one of them is optional. Simple examples In this section, we aim to explore a couple of examples of using the for loop. With each example,...
In the example below, the car object contains various properties. We used the forin loop to traverse through each key of the object.In the output, we can see that it prints the key and its value. We use the '[]' (member of) operator to access the value of the key from the ...
For loop example over an iterable object In the following example, we’re looping over the variableobjand logging each property and value: constobj={"a":"JavaScript",1:"PHP","b":"Python",2:"Java"};for(letkeyinobj){console.log(key+": "+obj[key])}// Output:// "1: PHP"// "...