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...
conststring ='code';// using for...in loopfor(letiinstring) {console.log(string[i]); }; Run Code Output c o d e JavaScript for...in With Arrays You can also usefor...inwitharrays. For example, // define arrayconstarr = ["hello",1,"JavaScript"];// using for...in loopfor(...
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...
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 ...
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...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...
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....
A for…in loop string example In the example below, we’re looping over the following variablestr: conststr="Hello!";for(letkeyinstr){console.log(key+": "+str.charAt(key));}//Output// "0: H"// "1: e"// "2: l"// "3: l"// "4: o"// "5: !" ...
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 =...