JavaScript for Loop | jquery for loop
Loopscanexecuteablockofcodeanumberoftimes.JavaScriptLoopsLoopsarehandy,ifyouwanttorunthesamecodeoverandoveragain,eachtimewithadifferentvalue.Oftenthisisthecasewhenworkingwitharrays:Insteadofwriting:text+=cars[0]+"
";text+=cars[1]+"
";text+=cars[2]+"
";text+=cars[3]+"
";text+=cars[4]+"
";text+=cars[5]+"
";Youcanwrite:for(leti=0;i
Loops can execute a block of code a number of times.
JavaScript LoopsLoops are handy, if you want to run the same code over and over again, each time with a different value.
Often this is the case when working with arrays:
Instead of writing:text += cars[0] + "<br>"; text += cars[1] + "<br>"; text += cars[2] + "<br>"; text += cars[3] + "<br>"; text += cars[4] + "<br>"; text += cars[5] + "<br>";
You can write:for (let i = 0; i < cars.length; i++) { text += cars[i] + "<br>";}
Try it Yourself »[1] Different Kinds of LoopsJavaScript supports different kinds of loops:
for - loops through a block of code a number of times for/in - loops through the properties of an object for/of - loops through the values of an iterable object while - loops through a block of code while a specified condition is true do/while - also loops through a block of code while a spe...