Skip to content
  • Strings & Template Literals · JavaScript

Strings & Template Literals

LearnViaNotes @learnvianotes· 1 min read

Strings are immutable sequences of UTF-16 code units. Template literals give interpolation, multi-line text and tagged templates.

Three ways to write a string

JavaScript
const single = 'single';
const double = "double";
const name = "Asha";
const tpl = `Hi ${name}, 2 + 3 = ${2 + 3}, upper: ${name.toUpperCase()}`;
console.log(single, double);
console.log(tpl);
const multi = `line 1
line 2`;
console.log(multi);
Output
single double
Hi Asha, 2 + 3 = 5, upper: ASHA
line 1
line 2

Indexing and immutability

JavaScript
const s = "JavaScript";
console.log(s.length, s[0], s.at(-1), s.charAt(4), s[99]);
console.log(s.slice(0, 4), s.slice(-6), s.substring(4, 0));
console.log(s.charCodeAt(0), String.fromCharCode(74));
Output
10 J t S undefined
Java Script Java
74 J

Unicode gotcha

JavaScript
const emoji = "😀";
console.log(emoji.length, [...emoji].length);
console.log("héllo".length, "héllo".normalize("NFD").length);
const flag = "👍🏽";
console.log(flag.length, [...flag].length);
Output
2 1
5 6
4 2

Escapes and raw strings

JavaScript
console.log("tab:\tend", "quote: \"", 'it\'s');
console.log("\u0041\u{1F600}");
console.log(String.raw`C:\new\table`);
Output
tab:	end quote: " it's
A😀
C:\new\table

Tagged templates

A tag is a function called with the literal's string pieces and the interpolated values — used by String.raw, styled-components, GraphQL gql, SQL builders and HTML escapers.

JavaScript
function highlight(strings, ...values) {
  return strings.reduce(
    (out, str, i) => out + str + (i < values.length ? `[${values[i]}]` : ""),
    ""
  );
}
const item = "coffee", price = 3.5;
console.log(highlight`One ${item} costs $${price}.`);

function show(strings, ...values) {
  console.log(strings, values);
}
show`a${1}b${2}`;
Output
One [coffee] costs $[3.5].
[ 'a', 'b', '' ] [ 1, 2 ]

Why is "😀".length equal to 2?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report