DEV Community

Anandhi P
Anandhi P

Posted on

Loop in JavaScript

A loop is used to repeat a block of code again and again.

Types of Loops

1. for Loop

Used when we know how many times to repeat.

for (let i = 1; i <= 5; i++) {
    console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

Output:
1 2 3 4 5

2. while Loop

Runs while the condition is true.

let i = 1;

while (i <= 5) {
    console.log(i);
    i++;
}
Enter fullscreen mode Exit fullscreen mode

3. do...while Loop

Runs the code at least one time.

let i = 1;

do {
    console.log(i);
    i++;
} while (i <= 5);
Enter fullscreen mode Exit fullscreen mode

4. for...of Loop

Used to get values from an array.

let fruits = ["Apple", "Mango"];

for (let fruit of fruits) {
    console.log(fruit);
}
Enter fullscreen mode Exit fullscreen mode

5. for...in Loop

Used to get keys from an object.

let person = {name: "Anandhi", age: 21};

for (let key in person) {
    console.log(key);
}
Enter fullscreen mode Exit fullscreen mode

break

break is used to stop the loop.

if (i == 3) {
    break;
}
Enter fullscreen mode Exit fullscreen mode

continue

continue is used to skip the current iteration.

if (i == 3) {
    continue;
}
Enter fullscreen mode Exit fullscreen mode

Nested Loop

A loop inside another loop is called a nested loop.

for (let i = 1; i <= 2; i++) {
    for (let j = 1; j <= 3; j++) {
        console.log(i, j);
    }
}
Enter fullscreen mode Exit fullscreen mode
  • for → Repeat a fixed number of times
  • while → Repeat while condition is true
  • do...while → Runs at least once
  • for...of → Gets values
  • for...in → Gets keys
  • break → Stops loop
  • continue → Skips one iteration
  • Nested loop → Loop inside another loop

qUESTION:

String.fromCharCode(64 + i) என்னன்னா, number-ஐ letter-ஆ மாற்றுவது.

Example:

let i = 1;

String.fromCharCode(64 + i)

Step by step:

i = 1
64 + 1 = 65
65 → A

அதனால் output A.

Next:

i = 2
64 + 2 = 66
66 → B

1 → A
2 → B
3 → C
4 → D
...
26 → Z

Top comments (0)