Skip to main content

Command Palette

Search for a command to run...

Loops and strings

Updated
β€’4 min readβ€’View as Markdown

πŸ” 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! ✨