Code of the Day
BeginnerLanguage basics

Strings and template literals

Work with text, and build it cleanly with template literals.

JavaScript / TSBeginner8 min read
Recommended first
By the end of this lesson you will be able to:
  • Use common string methods
  • Build strings with template literals
  • Know that strings are immutable

Text handling is daily work. JavaScript strings are immutable sequences of characters with a useful set of methods, plus a clean syntax for building text from values.

Common methods

String methods return new strings (the original never changes):

"  hi  ".trim();           // "hi"
"Hello".toUpperCase();     // "HELLO"
"a,b,c".split(",");        // ["a", "b", "c"]
"hello".includes("ell");   // true
"hello".slice(0, 3);       // "hel"
"hello".replace("l", "L"); // "heLlo"  (first match)

Template literals

To insert values into text, use a — a string written with backticks, where ${ } embeds any expression:

const name = "Ada";
const age = 36;
const msg = `${name} is ${age}`;          // "Ada is 36"
const next = `next year: ${age + 1}`;     // "next year: 37"

Template literals also span multiple lines directly, and they're far clearer than gluing strings with +. Prefer them whenever you're combining text and values.

Strings are immutable

You can read a character by index, but you can't change one in place:

const s = "cat";
s[0];        // "c"
s[0] = "b";  // silently does nothing — strings can't be mutated

To "change" a string, build a new one (e.g. with replace or slice).

JavaScript — editable, runs in your browser

Where to go next

Next: arrays and objects — JavaScript's two core ways to structure data.

Finished reading? Mark it complete to track your progress.

On this page