JS LOOPS

Lavanya



JavaScript Loop Statement

JavaScript loops, such as for, while, do-while, and for-in, are used to iterate over code, making it more concise. They are commonly used with arrays.

JavaScript has four types of loops.
1.  for loop
2.  while loop
3.  do-while loop
4.  for-in loop

JavaScript for Loop

The JavaScript `for` loop iterates over elements a fixed number of times. It is best used when the number of iterations is known. The syntax for the `for` loop is shown below.

Syntax:

for (initialization; condition; increment/decrement) {
  // code block to be executed
}

Example:

Here's a simple example of a `for` loop in JavaScript.

<Script>

for (let i = 0; i < 5; i++) {
  console.log("Hello, World!");
}

</Script>

Output:

Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!

JavaScript while Loop

The JavaScript `while` loop can iterate indefinitely. It is best used when the number of iterations is unknown. The syntax for the `while` loop is shown below.

Syntax:

while (condition) {
  // code block to be executed
}

Example:

Here’s a simple example of a while loop in JavaScript.

<Script>

let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}

</Script>

Output:

0
1
2
3
4

JavaScript do while Loop

The JavaScript do-while loop, like the while loop, can iterate indefinitely. However, unlike the while loop, the code inside a do-while loop is executed at least once, regardless of whether the condition is true or false. The syntax of the do-while loop is shown below.

Syntax:

do {
  // code block to be executed
} while (condition);

Example:

<Script>

let i = 0;
do {
  console.log(i);
  i++;
} while (i < 5);

</Script>

Output:

0
1
2
3
4

JavaScript for in Loop

The JavaScript for-in loop is used to iterate over the properties of an object. 

Syntax:

for (variable in object) {
  // code block to be executed
}

Example:

let person = {name: 'John', age: 30, city: 'New York'};
for (let prop in person) {
  console.log(prop + ': ' + person[prop]);
}

Output:

name: John
age: 30
city: New York




More topic in JavaScript

Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send