Loops and strings

agastya shuklaagastya shukla
4 min read

๐Ÿ” Mastering JavaScript Strings and Loops โ€“ A Beginner-Friendly Guide

Whether you're just starting with JavaScript or brushing up your basics, two of the most important building blocks you'll use constantly are strings and loops.

Strings help us work with text, and loops help us repeat tasks. When combined, they unlock the ability to process and manipulate data in powerful ways.

In this blog post, we'll cover:

  • What strings are and how to use them

  • Common string methods

  • Different types of loops

  • How to use loops with strings

  • Real-world coding examples

Letโ€™s dive in! ๐Ÿ‘‡


๐Ÿ“ฆ What is a String in JavaScript?

A string is simply a sequence of characters enclosed in quotes. You can use single ('), double ("), or backticks (` ) for template literals.

let name = "John";
let greeting = 'Hello';
let sentence = `My name is ${name}`; // Template literal

Strings can contain letters, numbers, symbols, and spaces. JavaScript strings are immutable, which means you canโ€™t change them directly โ€” but you can create modified copies.


๐Ÿ› ๏ธ Useful JavaScript String Methods

Here are some commonly used methods that make string manipulation easy:

let str = " JavaScript is fun! ";

console.log(str.length);            // 20
console.log(str.trim());            // "JavaScript is fun!"
console.log(str.toUpperCase());     // " JAVASCRIPT IS FUN! "
console.log(str.toLowerCase());     // " javascript is fun! "
console.log(str.includes("Script"));// true
console.log(str.charAt(5));         // "c"
console.log(str.slice(0, 10));      // " JavaScrip"
console.log(str.split(" "));        // ["", "JavaScript", "is", "fun!"]

๐Ÿ” What is a Loop?

A loop allows you to run a block of code multiple times. JavaScript supports several types of loops. Letโ€™s look at each one:

๐Ÿ”น for loop

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

๐Ÿ”น while loop

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

๐Ÿ”น do...while loop

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

๐Ÿ”น for...of loop

Great for working with strings and arrays.

let word = "loop";

for (let char of word) {
  console.log(char);
}

๐Ÿ”„ Loops + Strings: Real Examples

Letโ€™s combine the two concepts and explore some practical examples.


โœ… Example 1: Print Each Character of a String

let text = "Code";

for (let i = 0; i < text.length; i++) {
  console.log(text[i]);
}

โœ… Example 2: Count Vowels in a String

let input = "Loops and Strings";
let vowels = "aeiouAEIOU";
let count = 0;

for (let char of input) {
  if (vowels.includes(char)) {
    count++;
  }
}

console.log("Total vowels:", count); // Output: 5

โœ… Example 3: Reverse a String

let original = "JavaScript";
let reversed = "";

for (let i = original.length - 1; i >= 0; i--) {
  reversed += original[i];
}

console.log(reversed); // Output: tpircSavaJ

โœ… Example 4: Check for Palindrome

function isPalindrome(str) {
  let reversed = "";
  for (let i = str.length - 1; i >= 0; i--) {
    reversed += str[i];
  }
  return str === reversed;
}

console.log(isPalindrome("madam")); // true
console.log(isPalindrome("loop"));  // false

โœ… Example 5: Capitalize First Letter of Each Word

let sentence = "javascript is amazing";
let words = sentence.split(" ");
let result = "";

for (let word of words) {
  result += word[0].toUpperCase() + word.slice(1) + " ";
}

console.log(result.trim()); // JavaScript Is Amazing

๐Ÿš€ Bonus Challenge: Compress a String

Input: "aaabbccaa"
Output: "a3b2c2a2"

function compressString(str) {
  let result = "";
  let count = 1;

  for (let i = 0; i < str.length; i++) {
    if (str[i] === str[i + 1]) {
      count++;
    } else {
      result += str[i] + count;
      count = 1;
    }
  }

  return result;
}

console.log(compressString("aaabbccaa")); // a3b2c2a2


๐Ÿ Final Thoughts

Understanding strings and loops is essential to becoming a proficient JavaScript developer. They form the foundation of real-world programming tasks like input validation, data processing, algorithms, and more.

Once you're confident with these, try combining them to solve coding challenges and mini projects!

If you enjoyed this post, share it with your dev friends or drop a comment. ๐Ÿ‘‡

Happy coding! โœจ


0
Subscribe to my newsletter

Read articles from agastya shukla directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

agastya shukla
agastya shukla