You are on page 1of 9
Loops in JavaScript Lhe 3 é Gioba Teele ales Swipe — 2/9 What are loops and why are they used? Loops are handy, if you want to run the same code over and over again, each time with a different value. eee oN text += cars[0] + "
"; Inst, Cte ean Ley amare th text += cars[2] + "
"; text += cars[3] + "
"; text += cars[4] + "
"; Ao sae eae coo for (let i = 0; i < cars.length; i++) wae ae) re pee rear ee ae a a } a cy Swipe — Jk hy) Types 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 specified condition is true Swipe — ve 1. For loop SORES a) a // code block to be executed Statement 1 is executed (one time) before the execution of the code block. Statement 2 defines the condition for executing the code block. Statement 3 is executed (every time) after the code block has been executed. eee for (let i = 0; i < cars.length; i++) at text += cars[i] + "
"; Ip hy) Swipe — ed 2. For/in loop eee The JavaScript for in an (cy a) carey a statement loops ; Tn Ce eat) through the properties + of an Object eee const person = {fname:"John", name: "Doe", age:25}; at ae Coa for (let x in person) { text += person[x]; + falcon + The for in loop iterates over a person object + Each iteration returns a key (x) + The key is used to access the value of the key * The value of the key is person[x] Swipe — hy) Yad 3. For/of loop OOO The JavaScript for of eCraC Cnc Ct statement loops le Sree) through the values of y an iterable object. It lets you loop over iterable data structures such as Arrays, Strings, Maps, NodeLists, and more variable - For every iteration the value of the next property is assigned to the variable. Variable can be declared with const, let, or var. iterable - An object that has iterable properties. Cr) const cars = ["BMW", "Volvo", "Mini"]; Can cae for (let x of cars) { anor g a hy) Swipe — 7/9 4. While loop eee The while loop loops “Tine (Genesio % through a block of code eT Ne eh as long as a specified t condition is true. Cae while (i < 10) { cca CSM eon ws Bu Moree Masao) ae a) ON a aL on a variable (i) is less than 10 Swipe — hy) 8/9 5. Do While loop The do while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. Clg a) 4 eo rt oon a Pa GeO £ Taree macro t iy nd te Si ra) ory = aT heer Scone cy Swipe — Slobodan Gajié Content Creator oe baal} ye) FOLLOW FOR MORE

You might also like