Strings are immutable sequences of UTF-16 code units used to represent textual data. In JavaScript, strings can be declared using single quotes ('), double quotes ("), or template literals (`).
flowchart LR
StringVal["String: 'KodSolution'"] --> Index0["[0]: 'K'"]
StringVal --> Index1["[1]: 'o'"]
StringVal --> Index2["[2]: 'd'"]
StringVal --> Length["length property: 11"]
| Declaration Style | Syntax | Supports Interpolation? | Supports Multiline? |
|---|---|---|---|
| Single Quotes | 'Hello World' |
No | No (Requires ` |
| `) | |||
| Double Quotes | "Hello World" |
No | No (Requires ` |
| `) | |||
| Template Literal | `Hello ${name}` |
Yes (${expr}) |
Yes |
// Demonstrating String properties, character access, and immutability
const siteName = "KodSolution";
// 1. Accessing Characters and Length
console.log(`Site Name Length: ${siteName.length}`); // 11
console.log(`Character at index 0 (bracket): ${siteName[0]}`); // 'K'
console.log(`Character at index 3 (charAt): ${siteName.charAt(3)}`); // 'S'
// 2. Escape Characters
const escapedString = "Line 1
Line 2 Tabbed "Quoted Text" \ Backslash";
console.log("Escaped String Output:
" + escapedString);
// 3. String Immutability Demonstration
let title = "javascript";
title[0] = "J"; // Bracket assignment silently fails on primitives!
console.log(`Title after index assignment attempt: ${title}`); // "javascript" (Unchanged!)
// Correct way: Re-assign a new string
title = title.charAt(0).toUpperCase() + title.slice(1);
console.log(`Corrected Title: ${title}`); // "Javascript"
// 4. Iterating over String Characters
console.log("--- Character Iteration ---");
for (const char of "JS") {
console.log(`Char: ${char}`);
}
toLowerCase(), replace()) returns a NEW string; it never mutates the original string.+ string concatenation.🚀) consist of two UTF-16 code units, so "🚀".length returns 2. Use spread [..."🚀"].length for Unicode-aware character counts.Write a function capitalizeFirstLetter(str) that accepts a string and returns the string with its first letter capitalized.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.