Reading — step 1 of 7
Learn
Strings are sequences of characters wrapped in quotes. JavaScript accepts three quote styles, all producing the same kind of string:
Pick a style and stick with it. Most projects use single quotes for normal strings, backticks when you need to interpolate (next lesson).
Length and indexing
Indexing is zero-based. Out-of-range returns undefined (not an error — a classic footgun).
Strings are IMMUTABLE
You can't change a character in place. Methods that "modify" actually return a NEW string:
Slicing — extract substrings
slice is the modern, recommended method. (Older code uses substring and substr — they have quirks; prefer slice.)
Common string methods
Iterating characters
for...of correctly handles Unicode (including emojis). Indexing with s[i] works on UTF-16 code units, which can split certain emojis.
Converting between types
Template literals also coerce automatically.
Common mistakes
- Trying to mutate:
s[0] = "X"silently fails. Build a new string. - Forgetting that
replaceonly replaces the FIRST match — usereplaceAll. - Using
indexOf's -1 in a truthy context:if (s.indexOf("x"))misfires both ways — a match at index 0 gives0(falsy, so the branch is skipped) while no match gives-1(truthy, so the branch runs). Compare to-1explicitly.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…