Loops help to automate repetitive tasks in programming until the certain condition is met. JavaScript provides different types of looping to run a block of code.
Loop Types in JavaScript
- for loop
- for in loop
- while loop
- do-while loop
Let’s dive into details on each type.
1: for Loop
for loop is a most frequently used loop in javascript. It consists of 3 parts i.e.loop initializer, test statement and iteration statement. loop initializer is executed only once before the loop begins. test statement helps to determine whether a condition is true or not. If the condition is true, code inside of loop is executed else code inside loop is escaped. Lastly, iteration statement is used to increment or decrement the value of test statement. This is executed on every loop.
Syntax of for loop
for (statement 1; statement 2; statement 3) { code block to be executed }
Example of for loop
var sum = 0; for (var i = 1; i2: for in loop
for in loop iterate through the properties of object. The block of code inside the loop will be executed once for each property.
Syntax of for..in loop
for (var in object) { code block to be executed }Example of for..in loop
var customer = { name:"Vijay", age: 30, degree: "Masters", location: "Nepal" }; for (var item in customer) { alert(customer[item]); } //output: "Vijay", 30, "Masters", "Nepal"3: while loop
while loop is also frequently used loop in javascript. While loop executes a block of code as long as the condition specified is true.
syntax of while loop
while (condition) { code block to be executed }Example of while loop
var sum = 0; var number = 1; while (number4: do-while loop
do-while loop is similar to while loop except that the condition check done at the end of loop. Due to this, block of code inside loop is executed at least once.
syntax of do-while loop
do{ code block to be executed } while (condition);Example of do-while loop
Below is a simple example of do-while loop.
var sum = 0; var number = 1; do { sum += number; // -- body number++; // -- updater } while (numberHope you understand the loops in javascript. You can learn more about basics of javascript in this article. Happy Coding 🙂