Introduction Of Strings

Posted on January 13, 2025 by Vishesh Namdev
Python C C++ Javascript Java
Introduction of Strings in JS

Introduction of Strings
A string in JavaScript is a sequence of characters used to represent text. Strings are enclosed in single quotes ('), double quotes ("), or backticks (`). They are immutable, meaning once a string is created, its content cannot be changed (though you can assign a new string to the same variable).

Defining Strings

1. Single quotes (')
let singleQuoteString = 'Hello, World!';
2. Double quotes(")
let doubleQuoteString = "Hello, World!";
3. Template Literals
let backtickString = `Hello, Template Literals!`;

Template Literals
Template literals are a modern way of working with strings in JavaScript, introduced in ES6. They are enclosed by backticks (`) and allow embedding expressions using the syntax ${expression}. They also support multi-line strings without needing escape characters.

Features of Template Literals:
  • Expression Interpolation: You can include variables and expressions directly in a string using ${}
  • const name = 'Alice';
      const age = 25;
      console.log(`My name is ${name} and I am ${age} years old.`);
      // Output: My name is Alice and I am 25 years old.

  • 2. Multi-Line Strings: Template literals let you create multi-line strings easily.
  • const multiLine = This is a 
      multi-line
      string.; 
      console.log(multiLine);

    Escape Sequences
    Escape sequences in JavaScript are used to include special characters within a string. They begin with a backslash (\), followed by a character that represents the desired special character.

    Common Escape Sequences:
  • \' - Single Quote
  • \" - Double Quote
  • \\ - Backslash
  • \n - Newline
  • \t - Tab
  • \r - Carriage Return
  • \b - Backspace
  • \f - Form Feed
  • \uXXXX - Unicode Character
  • Example of Escape Sequence

    let singleQuote = 'It\'s a sunny day!'; // Escaping a single quote
        let doubleQuote = "She said, \"Hello!\""; // Escaping a double quote
        let newLine = "Hello\nWorld!"; // Newline
        let tab = "Name\tAge"; // Tab
        
        console.log(singleQuote); // It's a sunny day!
        console.log(doubleQuote); // She said, "Hello!"
        console.log(newLine);
        // Output:
        // Hello
        // World!
        console.log(tab); // Name Age
    ๐Ÿ“ขImportant Note๐Ÿ“ข

    How did you feel about this post?

    ๐Ÿ˜ ๐Ÿ™‚ ๐Ÿ˜ ๐Ÿ˜• ๐Ÿ˜ก

    Was this helpful?

    ๐Ÿ‘ ๐Ÿ‘Ž