Skip to content
String Basics
step 1/7

Reading — step 1 of 7

Learn

~2 min readStrings

Strings are sequences of characters wrapped in quotes. JavaScript accepts three quote styles, all producing the same kind of string:

js

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

js

Indexing is zero-based. Out-of-range returns undefined (not an error — a classic footgun).

Strings are IMMUTABLE

js

You can't change a character in place. Methods that "modify" actually return a NEW string:

js

Slicing — extract substrings

js

slice is the modern, recommended method. (Older code uses substring and substr — they have quirks; prefer slice.)

Common string methods

js

Iterating characters

js

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

js

Template literals also coerce automatically.

Common mistakes

  • Trying to mutate: s[0] = "X" silently fails. Build a new string.
  • Forgetting that replace only replaces the FIRST match — use replaceAll.
  • Using indexOf's -1 in a truthy context: if (s.indexOf("x")) misfires both ways — a match at index 0 gives 0 (falsy, so the branch is skipped) while no match gives -1 (truthy, so the branch runs). Compare to -1 explicitly.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…

String Basics — JavaScript Fundamentals