Strings

Strings are sequences of characters used to represent text in JavaScript. They are one of the most common data types and are enclosed in quotes.

  • Syntax: Strings can be defined using single quotes (' '), double quotes (" "), or backticks (` `).
  • Backticks allow for template literals which support multi-line strings and interpolation.
Illustration of strings
Illustration of strings

💡 String Delimiters

Use single or double quotes for simple strings. For embedding variables or multi-line text, use backticks.

String Declaration Examples
TypeExampleNotes
Single quotes'Hello'Basic string
Double quotes"World"Same as single quotes
Backticks`Hello, ${name}!`Template literals with interpolation

Common String Operations

  • Concatenation: Combine strings using the + operator.
  • Length: Get the number of characters with .length.
  • Access Characters: Use bracket notation str[index] to access a character.
  • Methods: Strings have many built-in methods like toUpperCase(), toLowerCase(), includes(), slice(), and more.
Useful String Methods
MethodDescription
toUpperCase()Converts string to uppercase
toLowerCase()Converts string to lowercase
includes(substring)Checks if substring exists
slice(start, end)Extracts a part of the string
trim()Removes whitespace from both ends

📌 Deep Dive: Template Literals and Interpolation

JAVASCRIPT
const name = 'Alice';
const age = 25;

// Using concatenation
const greeting1 = 'Hello, ' + name + '! You are ' + age + ' years old.';

// Using template literals
const greeting2 = `Hello, ${name}! You are ${age} years old.`;

console.log(greeting1);
console.log(greeting2);
Output
Hello, Alice! You are 25 years old. Hello, Alice! You are 25 years old.

⚠️ Strings are Immutable

You cannot change a character inside a string directly. Operations that modify strings return new strings instead.

Escaping Characters

Use a backslash \ to escape special characters inside strings, like quotes or newlines.

📌 Deep Dive: Escaping Quotes and Newlines

JAVASCRIPT
const quote = 'She said, \'Hello!\'';
const multiline = "Line1
Line2";

console.log(quote);
console.log(multiline);
Output
She said, 'Hello!' Line1 Line2

💡 String Indexing

String characters are zero-indexed. For example, str[0] accesses the first character.