DEV Community

dharanidharan
dharanidharan

Posted on

JavaScript-Loops & Strings

Loops

Imagine you had to write console.log() 100 times just to print numbers 1 to 100. Sounds exhausting, right? That's exactly the problem loops solve — they let you repeat a task without repeating your code.

1. The for Loop

The most common loop. It's perfect when you know exactly how many times you want to repeat something.

example

for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Output: 1 2 3 4 5

Here's what's happening:
let i = 1 — start counting at 1
i <= 5 — keep going while this is true
i++ — add 1 after each round

2. The while Loop

Use this when you don't know in advance how many times you'll loop ,you just know the condition that should keep it going.

example

let count = 1;
while (count <= 5) {
console.log(count);
count++;
}

It checks the condition before running, so if the condition is false right away, the loop never runs at all.

4. The for...of Loop

Great for looping through arrays (or any iterable) when you just want the values.

example
const fruits = ["apple", "banana", "mango"];
for (const fruit of fruits) {
console.log(fruit);
}

Reference

Strings

A string is just text — a name, a sentence, a URL, anything wrapped in quotes. It's one of the first data types you'll use in JavaScript, so let's cover the basics.

example
let text = "John Doe";

String Methods

  • length – Find string length.
  • toUpperCase() – Convert to uppercase.
  • toLowerCase() – Convert to lowercase.
  • trim() – Remove extra spaces.
  • charAt() – Get a character by index.
  • indexOf() – Find the position of a character or word.
  • includes() – Check if text exists.
  • slice() – Extract part of a string.
  • replace() – Replace text.
  • split() – Convert a string into an array.

Reference

Top comments (0)