Lesson

JS Strings

10 min reading
Free Course

JavaScript Strings: Quotes, Immutability, and Indexing

A JavaScript string is an immutable sequence of UTF-16 characters used to represent text. You can create strings with single quotes ('...'), double quotes ("..."), or backticks (`...`).

Quotes, Escapes, and Immutability

Single and double quotes behave identically, so pick one style and stay consistent. Backticks create template literals that span multiple lines and embed expressions with ${...}.

Strings in JavaScript cannot be changed in place. Trying word[0] = "H" silently fails (or throws a TypeError in strict mode); you must create a new string instead.

Accessing Characters and Length

Read .length to count UTF-16 code units, or use .at(-1) (ES2022) to read the last character cleanly without writing str[str.length - 1].

const city = "Chattogram";
const quote = 'She said, "Code runs cleanly!"';
const multiLine = `City: ${city}
Length: ${city.length}`;

console.log("First char:", city[0]);
console.log("Last char:", city.at(-1));
console.log(quote);
console.log(multiLine);

Common Escape Sequences

  • : Inserts a newline character inside quoted strings.
  • : Inserts a horizontal tab space.
  • \\: Writes a literal backslash character, useful for Windows file paths.
  • \" or \': Escapes a matching quote inside the same quote style.

Common Mistakes to Avoid

  • Wrapping strings with new String("abc"): Calling new String() creates an object wrapper instead of a primitive string, which breaks === comparisons and slows code down.
  • Assuming .length counts visual emojis accurately: Complex emojis use two UTF-16 units, so "πŸš€".length is 2. Use [..."πŸš€"].length when counting visual characters.
  • Using + across long multi-line strings: Template literals with backticks handle multi-line text cleanly without manual escapes.

Frequently Asked Questions

Are single quotes or double quotes faster in JavaScript?

No, single quotes and double quotes compile to the exact same internal string representation and run at identical speed.

How do I convert another type into a string?

Use String(value) because it safely converts null to "null" and undefined to "undefined" without throwing errors.

Why does str.at(-1) beat str[str.length - 1]?

str.at(-1) is shorter, reads from the end naturally, and avoids repeating the variable name.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
JavaScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum