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...
Let's look at an example that shows how to use a for-in loop in JavaScript. For example: var totn_colors = { primary: 'blue', secondary: 'gray', tertiary: 'white' }; for (var color in totn_colors) { console.log(totn_colors[color]); } In this example, the following will be...
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...
Example 1: Print Numbers From 1 to 5 for (let i = 1; i < 6; i++) { console.log(i); } Run Code Output 1 2 3 4 5 In this example, we have printed numbers from 1 to 5 using a for loop. Here is how this program works: IterationVariableCondition: i < 6Action 1st i =...
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 ...
The loop counter i.e. variable in the for-in loop is a string, not a number. It contains the name of current property or the index of the current array element.The following example will show you how to loop through all properties of a JavaScript object....
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...
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...
Using let in a loop:Example let i = 5; for (let i = 0; i < 10; i++) { // some code} // Here i is 5 Try it Yourself » In the first example, using var, the variable declared in the loop redeclares the variable outside the loop. ...
element- items in the iterable In plain English, you can read the above code as: for every element in the iterable, run the body of the loop. for...of with Arrays Thefor..ofloop can be used to iterate over anarray. For example, ...