JavaScript String Data Type
String Basics
Strings are used to store and manipulate text data in JavaScript. They are primitive data types and are immutable.
1// String declaration examples
2let message = "Hello World";
3const name = 'John Doe';
4const greeting = `Hello ${name}`;
5
6console.log(message); // Output: "Hello World"
7console.log(name); // Output: "John Doe"
8console.log(greeting); // Output: "Hello John Doe"String Characteristics
Primitive Type- Strings are one of JavaScript's primitive data typesImmutable- Cannot be changed once created - operations return new stringsText Storage- Used to store and manipulate textual dataUTF-16 Encoded- Supports international characters and emojis
String Declaration Methods
Strings can be declared using single quotes, double quotes, or template literals with different use cases for each.
1// Different ways to declare strings
2let singleQuotes = 'Hello World';
3let doubleQuotes = "Hello World";
4let templateLiteral = `Hello World`;
5
6// Template literals allow embedded expressions
7let firstName = "John";
8let lastName = "Doe";
9let fullName = `My name is ${firstName} ${lastName}`;
10
11// Quotes within strings
12let quoteInString1 = "He said, 'Hello World'";
13let quoteInString2 = 'She said, "Hello World"';
14let quoteInString3 = `They said, "It's amazing!"`;
15
16console.log(singleQuotes); // Output: "Hello World"
17console.log(doubleQuotes); // Output: "Hello World"
18console.log(templateLiteral); // Output: "Hello World"
19console.log(fullName); // Output: "My name is John Doe"
20console.log(quoteInString1); // Output: "He said, 'Hello World'"
21console.log(quoteInString2); // Output: "She said, \"Hello World\""
22console.log(quoteInString3); // Output: "They said, \"It's amazing!\""Declaration Types
Single Quotes- 'text' - Good for simple strings without apostrophesDouble Quotes- "text" - Good for strings with apostrophesTemplate Literals- `text` - Allows embedded expressions and multi-line stringsQuote Nesting- Use different quote types to include quotes within strings
String Properties and Methods
Strings have built-in properties and methods for manipulation, even though they are primitive types. JavaScript automatically wraps primitives in String objects when methods are called.
1let message = "Hello World";
2
3// String properties
4console.log(message.length); // Output: 11
5
6// Common string methods
7console.log(message.toUpperCase()); // Output: "HELLO WORLD"
8console.log(message.toLowerCase()); // Output: "hello world"
9console.log(message.charAt(0)); // Output: "H"
10console.log(message.indexOf("World")); // Output: 6
11console.log(message.lastIndexOf("l")); // Output: 9
12console.log(message.slice(0, 5)); // Output: "Hello"
13console.log(message.substring(6, 11)); // Output: "World"
14console.log(message.replace("World", "JavaScript")); // Output: "Hello JavaScript"
15console.log(message.split(" ")); // Output: ["Hello", "World"]
16console.log(message.trim()); // Output: "Hello World" (removes whitespace)
17console.log(message.startsWith("Hello")); // Output: true
18console.log(message.endsWith("World")); // Output: true
19console.log(message.includes("lo")); // Output: true
20
21// Accessing characters
22console.log(message[0]); // Output: "H"
23console.log(message[6]); // Output: "W"Common String Methods
Case Conversion- toUpperCase(), toLowerCase() - change string caseSearching- indexOf(), includes(), startsWith(), endsWith()Extraction- slice(), substring(), charAt() - get parts of stringModification- replace(), trim(), split() - transform strings
String Operations
Strings support various operations like concatenation, comparison, and searching. Understanding these operations is crucial for effective string manipulation.
1let str1 = "Hello";
2let str2 = "World";
3
4// Concatenation methods
5let concat1 = str1 + " " + str2;
6let concat2 = str1.concat(" ", str2);
7let templateConcat = `${str1} ${str2}`;
8
9console.log(concat1); // Output: "Hello World"
10console.log(concat2); // Output: "Hello World"
11console.log(templateConcat); // Output: "Hello World"
12
13// Comparison operations
14console.log(str1 === "Hello"); // Output: true
15console.log(str1 === "hello"); // Output: false
16console.log(str1 !== "World"); // Output: true
17
18// Case-insensitive comparison
19console.log(str1.toLowerCase() === "hello"); // Output: true
20
21// String searching
22let text = "Hello World, welcome to JavaScript";
23console.log(text.includes("World")); // Output: true
24console.log(text.startsWith("Hello")); // Output: true
25console.log(text.endsWith("JavaScript")); // Output: true
26
27// Repeating strings
28console.log("Ha".repeat(3)); // Output: "HaHaHa"
29
30// Padding strings
31console.log("5".padStart(3, "0")); // Output: "005"
32console.log("5".padEnd(3, "0")); // Output: "500"String Immutability
Strings are immutable - once created, they cannot be changed. All string operations return new strings rather than modifying the original.
1let originalString = "Hello World";
2
3// Attempting to modify a string creates a new one
4let modifiedString = originalString.replace("World", "JavaScript");
5
6console.log(originalString); // Output: "Hello World" (unchanged)
7console.log(modifiedString); // Output: "Hello JavaScript" (new string)
8
9// Direct modification doesn't work
10let testString = "Hello";
11testString[0] = "J"; // This won't change the string
12console.log(testString); // Output: "Hello" (still unchanged)
13
14// To "modify" a string, you must reassign it
15testString = "J" + testString.slice(1);
16console.log(testString); // Output: "Jello"
17
18// Multiple operations create multiple new strings
19let complexString = " Hello World ";
20let processedString = complexString.trim().toUpperCase().replace("WORLD", "UNIVERSE");
21
22console.log(complexString); // Output: " Hello World " (unchanged)
23console.log(processedString); // Output: "HELLO UNIVERSE" (new string)
24
25// Memory efficiency with large strings
26let longString = "This is a very long string...";
27// Each operation creates a copy, which can be memory-intensive for large stringsSpecial Characters and Escaping
Strings can contain special characters using escape sequences. This allows you to include characters that would otherwise be difficult to represent.
1// Escape sequences in strings
2let stringWithQuotes = "He said, \"Hello World!\"";
3let stringWithNewline = "Line 1\nLine 2";
4let stringWithTab = "Name:\tJohn";
5let stringWithBackslash = "Path: C:\\Users\\John";
6let stringWithCarriageReturn = "Loading...\rDone";
7
8console.log(stringWithQuotes); // Output: "He said, \"Hello World!\""
9console.log(stringWithNewline); // Output:
10 // "Line 1
11 // Line 2"
12console.log(stringWithTab); // Output: "Name: John"
13console.log(stringWithBackslash); // Output: "Path: C:\\Users\\John"
14
15// Unicode characters
16let unicodeString = "Hello \u{1F44B} World!";
17let heartSymbol = "I \u2665 JavaScript";
18let copyrightSymbol = "Copyright \u00A9 2024";
19
20console.log(unicodeString); // Output: "Hello 👋 World!"
21console.log(heartSymbol); // Output: "I ♥ JavaScript"
22console.log(copyrightSymbol); // Output: "Copyright © 2024"
23
24// Using String.fromCharCode()
25let fromCharCode = String.fromCharCode(65, 66, 67); // ABC
26console.log(fromCharCode); // Output: "ABC"
27
28// Template literals for multi-line strings
29let multiLineString = `This is a
30multi-line
31string without escape sequences`;
32
33console.log(multiLineString);
34// Output:
35// "This is a
36// multi-line
37// string without escape sequences"String Best Practices
Following best practices when working with strings leads to more efficient, readable, and maintainable code.
1// Use const for strings that don't change
2const API_URL = "https://api.example.com";
3const DEFAULT_LANGUAGE = "en";
4
5// Use template literals for complex strings
6const user = { name: "John", age: 30 };
7const greeting = `Hello ${user.name}, you are ${user.age} years old`; // GOOD
8// const greeting = "Hello " + user.name + ", you are " + user.age + " years old"; // LESS READABLE
9
10// Use descriptive variable names
11const errorMessage = "Invalid input"; // GOOD
12const msg = "Invalid input"; // BAD
13
14// Use includes() instead of indexOf() for existence checks
15const text = "Hello World";
16if (text.includes("World")) { // GOOD
17 console.log("Found World");
18}
19
20if (text.indexOf("World") !== -1) { // OK, but less clear
21 console.log("Found World");
22}
23
24// Cache string operations in loops
25const strings = ["hello", "world", "javascript"];
26
27// INEFFICIENT - creates new string each iteration
28for (let i = 0; i < strings.length; i++) {
29 console.log(strings[i].toUpperCase());
30}
31
32// EFFICIENT - cache the upperCase result
33for (let i = 0; i < strings.length; i++) {
34 const upperString = strings[i].toUpperCase();
35 console.log(upperString);
36}
37
38// Use String() for explicit conversion
39const number = 123;
40const stringNumber = String(number); // EXPLICIT AND CLEAR
41// const stringNumber = number.toString(); // ALSO GOOD
42// const stringNumber = number + ""; // IMPLICIT - LESS CLEAR