Strings: quotes, length and indexing

A JavaScript string is a sequence of UTF-16 code units, and this part of the course spends three lessons on it: this one on the value itself, the next on finding and taking parts, and the third on building text. The value is a primitive, so a string is compared, copied and passed by value like a number, and no function can change the string a caller holds.

The lesson starts with the three quote styles and the escape sequences that go inside them, then reads characters out of a string by index and shows what happens at the end. The third section proves the immutability with the error a write produces in strict mode, and the fourth covers the conversion between text and numbers that every form handler needs.

Three quote styles

Single quotes, double quotes and backticks all produce a string, and the first two are the same in every respect: they exist so that the other quote can appear inside without an escape. A backslash starts an escape sequence, so it has to be doubled to stand for itself, and the ones worth knowing are for a newline and \ for a backslash.

const single = 'plain'; const double = "plain"; const template = `backtick`; console.log(single, double, template); console.log('single is plain:', single === 'plain'); console.log('double is plain:', double === 'plain'); console.log('apostrophe:', 'it\'s here'); console.log('quoted:', "she said \"hi\""); console.log('windows path:', 'C:\temp'); console.log('length of the path:', 'C:\temp'.length); console.log('two lines:', 'one\ntwo');

node quotes.js

plain plain backtick
single is plain: true
double is plain: true
apostrophe: it's here
quoted: she said "hi"
windows path: C:\temp
length of the path: 7
two lines: one
two

The path is the line to read twice: eight characters stand between the quotes and seven are stored, because the doubled backslash is one character. A single backslash before a letter that has no escape meaning is dropped in the source and kept in the value, which is how a Windows path written carelessly loses its separators. The last line shows a real newline in the value, and the output prints it as two lines.

length and indexing

length counts the code units, and the bracket operator reads the unit at a position counted from zero. at takes a negative position and counts from the end, which the brackets cannot do. Past the end the bracket returns undefined and charAt returns an empty string, so the two disagree about a missing character.

const word = 'JavaScript'; console.log('length:', word.length); console.log('[0]:', word[0]); console.log('[4]:', word[4]); console.log('at(-1):', word.at(-1)); console.log('at(-4):', word.at(-4)); console.log('bracket past the end:', word[100]); console.log('charAt past the end is empty:', word.charAt(100) === ''); console.log('last index:', word.length - 1, word[word.length - 1]);

node indexing.js

length: 10
[0]: J
[4]: S
at(-1): t
at(-4): r
bracket past the end: undefined
charAt past the end is empty: true
last index: 9 t

The length is ten and the last index is nine, which is the off-by-one that a loop meets first. The two past-the-end lines are the reason to prefer one accessor: an empty string survives a string operation and undefined does not. The next lessons use slice and includes for whole pieces of text, and the bracket stays for a single character that is known to be there.

A string never changes

Every method that seems to change a string returns a new one, and the original keeps its value. A write to an index fails: in strict mode it throws a TypeError, and in sloppy mode it is silently ignored, which is worse. The file below declares strict mode at the top, which a module does by itself, and catches the error to print its message.

'use strict'; const word = 'cat'; try { word[0] = 'b'; } catch (error) { console.log(error.name + ': ' + error.message); } console.log('word still:', word); console.log('upper:', word.toUpperCase()); console.log('word after upper:', word); console.log('replaced copy:', word.replace('c', 'b'));

node immutable.js

TypeError: Cannot assign to read only property '0' of string 'cat'
word still: cat
upper: CAT
word after upper: cat
replaced copy: bat

The message names the property and the string, and it is the same one the runtime throws for a frozen object. The two methods returned new strings and left word as it was, so a program that calls toUpperCase and ignores the result does nothing at all. That property is what makes a string safe to share: a function that receives one cannot change what its caller sees.

Text and numbers

The plus sign joins text when one side is a string, and the order of the operands decides whether the other side is converted first. Number reads a whole string as a number and refuses anything else with NaN, and an empty string converts to zero, which is a trap in a form that submits a field the user left blank.

console.log('equal:', 'abc' === 'abc'); console.log('case matters:', 'abc' === 'ABC'); console.log('text plus number:', 'count: ' + 3); console.log('number plus text:', 3 + ' items'); console.log('sum first:', 3 + 4 + ' items'); console.log('from text:', Number('42'), Number('4.5')); console.log('refused:', Number('42px')); console.log('empty string:', Number('')); console.log('to text:', typeof String(42), String(undefined));

node convert.js

equal: true
case matters: false
text plus number: count: 3
number plus text: 3 items
sum first: 7 items
from text: 42 4.5
refused: NaN
empty string: 0
to text: string undefined

The two addition lines are the classic bug: 3 + 4 + ' items' adds first and joins after, so the sum appears, while ' items' + 3 + 4 would print the digits one after another. Number('42px') is NaN because the conversion is strict about the whole string, and parseInt is the function that reads a leading number and stops. The empty string is the case a form check has to test for before it converts.

Exercises

  1. Print 'a\tb' from quotes.js. How many characters does the value have, and what does the output show?
  2. Read word[word.length] in indexing.js. Which value arrives, and what does word.at(word.length) return?
  3. Remove 'use strict' from immutable.js and run it again. What happens to the first line of the output?
  4. Compare '10' < '9' and 10 < 9. Which of the two is true, and why does the text comparison differ?
  5. Convert ' 42 ' with Number and with parseInt. Which one accepts the spaces, and what does the other return?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which quote styles can produce a string?

    Answer

    Single quotes, double quotes and backticks

    All three are string delimiters, and the backtick adds interpolation and multi-line text.

  2. What does this program print? console.log('C:\\temp'.length);

    Answer

    7

    The doubled backslash is one stored character, so the letter C, the colon, the backslash and the four letters of temp make seven.

  3. What does this program print? const word = 'cat'; console.log(word[3]);

    Answer

    undefined

    A bracket read past the end returns undefined, which is why charAt is the safer accessor for text.

  4. What does 'JavaScript'.at(-1) return?

    Answer

    't'

    A negative position counts from the end, and the last character of the word is t.

  5. What does a write to word[0] do in strict mode?

    Answer

    It throws a TypeError, because the string is read only

    In strict mode the refused write is an error, and sloppy mode hides the same failure.

  6. Which of these changes the string in a variable called word?

    Answer

    None of them, every string method returns a new string

    The value is a primitive, so each method returns a new string and the binding keeps its value.

  7. What does this program print? console.log(3 + 4 + ' items');

    Answer

    7 items

    The addition happens first because it is on the left, and the join with the string comes after.

  8. What does this program print? console.log(Number(''));

    Answer

    0

    The empty string converts to zero, which is why a blank form field needs its own check.

  9. What does this program print? console.log(Number('42px'));

    Answer

    NaN

    Number reads the whole string and refuses trailing text, while parseInt stops at the first non-digit.

  10. What is the difference between word[0] at the end of a string and charAt there?

    Answer

    The bracket gives undefined and charAt gives an empty string

    The two accessors disagree about a missing character, and the empty string is the one that survives.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image