JavaScript String Values and Immutability
Quick answer
A String is a primitive sequence of UTF-16 code units. Strings represent text, and their values cannot be changed in place. Reassigning a variable to a new string is different from mutating the original string.
How it works
Use matching single or double quotes for a simple literal. The + operator combines strings when its primitive operands include a string. The length property counts UTF-16 code units, not necessarily visible characters. The notation text[0] reads the first code unit; string processing and Unicode details come later.
let text = "Hi";const original = text;text = text + "!";console.log(original);console.log(text);Expected output in Node.js:
HiHi!A new string was assigned to text.
Expected output in Node.js:
32The emoji uses a surrogate pair.
Common mistakes
Do not treat length as a count of user-perceived characters. Do not try to change text by assigning to an index; construct a new string instead. A string that contains digits is still text until converted.
Practice
Build a display label from an input string by adding a fixed prefix.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript String Values and Immutability — Knowledge Check
Apply the taught concept and reason about the result.
What does "😀".length return?
What does let a = "go"; const b = a; a = a + "!"; console.log(b); print?
What does string immutability mean?
Which result is produced by "7" + "2"?
What does text.length count?