1. Introduction: What is a String?

A string is a primitive data type in JavaScript used to represent a sequence of characters. Anything you can type—letters, numbers, symbols, punctuation—can be part of a string. It is the primary way we work with textual data.

Key Characteristics:


2. Creating Strings

There are three ways to create a string literal in JavaScript.

  1. Single Quotes ('...'):

    let singleQuoted = 'Hello, world!';
    
    
  2. Double Quotes ("..."): Functionally identical to single quotes. The main reason to choose one over the other is for convenience when a string itself contains quotes.

    let doubleQuoted = "He said, 'Hello!'"; // Easy to include single quotes
    let singleQuotedWithDouble = 'She replied, "Hi!"'; // Easy to include double quotes
    
    
  3. Template Literals (... - ES6): The most powerful and modern way. They use backticks. We will cover the special features of template literals later.

    let templateLiteral = `This is a template literal.`;
    
    

3. Core Properties and Concepts

A. The .length Property Every string has a .length property that tells you how many characters it contains.

let greeting = "Hello";
console.log(greeting.length); // Outputs: 5

let emptyString = "";
console.log(emptyString.length); // Outputs: 0

B. Accessing Individual Characters (Zero-Based Indexing) You can access a character at a specific position using square bracket notation []. The first character is at index 0.

let message = "JavaScript";
// J  a  v  a  S  c  r  i  p  t
// 0  1  2  3  4  5  6  7  8  9

console.log(message[0]); // "J"
console.log(message[4]); // "S"

// To get the last character, a common pattern is used:
console.log(message[message.length - 1]); // "t"

C. The Golden Rule: Strings are Immutable This is the most critical concept. You cannot change a string in place. Any method that appears to modify a string will always return a brand new string, leaving the original untouched.