Reading Characters With [] and at()
In this lesson, you ported the helper’s full-stop check and read single characters the JavaScript
way. The review bot rejects a commit subject that ends with a full stop, and PAY-2304’s title,
Retry failed card payments., has one.
- Python’s
len()function becomes thelengthproperty in JavaScript, read after a dot with no parentheses:title.lengthis27. Watch out:len()doesn’t exist in JavaScript, andtitle.length()is aTypeError, because a property isn’t a function. - Brackets read a position counted from the start, as in Python:
title[0]isR, andtitle[26], one less than the length, is the full stop. - JavaScript’s brackets don’t count from the end: they look up a position by its number, and the
string has no position
-1. The natural port of the check,const last = title[-1];, givesundefined, JavaScript’s value for nothing there, so the check printsEnds with a full stop: falsewhere Python printsTrue, with no error. - Reading a position that isn’t there gives
undefinedin JavaScript, with no error. A position past the end givesundefinedtoo, where Python raises anIndexError, so check the length when the text might be short. - To count from the end, use the
at()method: a negative position counts back from the end, as in a Python index, sotitle.at(-1)is the full stop. Like the brackets,at()givesundefined, not an error, when the position isn’t there. at()takes positions from the start too, but JavaScript code keeps the brackets for those and reaches forat()when it counts from the end.- As in Python, a string can’t change in place. In the helper’s port,
title[0] = "r"stops with aTypeError. - For text like these titles, each position holds one character. Text with emoji is where JavaScript’s positions and Python’s part ways, a later topic.
Here’s the check with the fix in place:
const title = "Retry failed card payments.";
const last = title.at(-1);
console.log(`Ends with a full stop: ${last === "."}`);