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...
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...
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...
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...
You can omit expression 1 when your values are set before the loop starts: Example leti =2; letlen = cars.length; lettext =""; for(; i < len; i++) { text += cars[i] +""; } Try it Yourself » You can intiate many values in expression 1 (separated by comma): Example...
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...
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 =...
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...
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....
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, ...