Strings
In JavaScript, textual data is stored in the string type. Standard strings can be enclosed in either single quotes (') or double quotes (").
'Hello'
"Hello"
While both are valid, consistency is important. Many teams adopt styling conventions—such as preferring double quotes—to keep project code unified and readable.
Indexing Characters
Strings are fundamentally sequences of characters. You can access individual characters within a string using square brackets []. JavaScript uses zero-based indexing, meaning the first character is at position 0.
const greeting = "Hello";
console.log(greeting[0]); // 'H'
console.log(greeting[1]); // 'e'
console.log(greeting[2]); // 'l'
String Length
Every string has a built-in .length property that returns the total number of characters it contains. Because indexing starts at 0, the final character of any string is always located at the index of length - 1.
const greeting = "Hello";
console.log(greeting.length); // 5
// Accessing the last character dynamically
console.log(greeting[greeting.length - 1]); // 'o'
Practical Example
You might need to parse user data, such as extracting specific characters from an email address to construct a profile avatar or obfuscate the address for security.
const email = "stoob@boot.dev";
// Access the first character
console.log("First char:", email[0]); // 's'
// Access the last character dynamically
console.log("Last char:", email[email.length - 1]); // 'v'
// Print the entire string
console.log("Full email:", email);