String Length and Positions
A string knows how long it is and lets you read any single character by its position, counting from zero.
length is a property, not a method, so it takes no brackets. Positions start at 0, so the last character is at length minus 1. Reading past the end gives undefined rather than an error.
EXERCISE
1length Is a Property, Not a Method
Every string carries a count of its characters, and it is read without brackets because it is a stored value rather than an action.
Reading the length:
const name = "JavaScript";
console.log(name.length); // 10
console.log("".length); // 0
console.log(" ".length); // 1 a space is a character
console.log(name.length()); // TypeError: name.length is not a function
// No brackets. It is a value, not an action.
A quick way to tell property from method:
const text = "hello";
// Properties: a stored value. No brackets.
console.log(text.length); // 5
// Methods: something the string DOES. Brackets, always.
console.log(text.toUpperCase()); // HELLO
console.log(text.toUpperCase); // [Function: toUpperCase] <- forgot them
Using length in real checks:
function validatePassword(password) {
if (password.length < 8) {
return "Too short";
}
if (password.length > 64) {
return "Too long";
}
return "Looks fine";
}
console.log(validatePassword("abc")); // Too short
console.log(validatePassword("correct-horse")); // Looks fine
Whitespace counts, which is worth remembering for forms:
const typed = " ";
console.log(typed.length); // 3 not empty!
console.log(typed.trim().length); // 0 now it is
if (typed.trim().length === 0) {
console.log("Please enter something");
}
length without brackets and toUpperCase() with them is the difference between a property and a method, and mixing them up gives two distinct symptoms: a method without brackets prints [Function], and a property with brackets throws "is not a function". Both tell you exactly which mistake you made.
EXERCISE
2Reading a Character by Position
Characters are numbered from zero, which means the last one always sits at length minus one.
Square brackets read a position:
const word = "cat";
console.log(word[0]); // c
console.log(word[1]); // a
console.log(word[2]); // t
// Position: c=0 a=1 t=2
// Length is 3, and the highest valid position is 2.
The last character, every time:
const word = "JavaScript";
console.log(word[word.length - 1]); // t
console.log(word[word.length]); // undefined <- off by one
// A newer, clearer way to say the same thing:
console.log(word.at(-1)); // t counts from the end
console.log(word.at(-2)); // p
Reading past the end is not an error:
const short = "hi";
console.log(short[5]); // undefined
console.log(short[5].length); // TypeError: Cannot read properties of undefined
// The first line is silent. The crash arrives on the next one,
// which is why off-by-one bugs are reported in the wrong place.
Walking every character:
const word = "cat";
for (let i = 0; i < word.length; i++) {
console.log(`${i}: ${word[i]}`);
}
// 0: c
// 1: a
// 2: t
// Or, without a counter at all:
for (const letter of word) {
console.log(letter);
}
Pro Tip:
length - 1for the last position is the arithmetic you will write more often than any other in this course, and it applies identically to arrays in the next unit. The reason it trips people is thatlengthcounts from one while positions count from zero, so the two are always exactly one apart.
EXERCISE
3Joining and Repeating Text
Building a longer string out of shorter ones comes up constantly, and there are three ways to do it that each suit a different job.
Concatenation with plus:
const first = "Ada";
const last = "Lovelace";
console.log(first + " " + last); // Ada Lovelace
console.log(first + last); // AdaLovelace <- the missing space bug
Template literals, which you met in Unit 2:
console.log(`${first} ${last}`); // Ada Lovelace
console.log(`${last}, ${first}`); // Lovelace, Ada
console.log(`${first.length} characters`); // 3 characters
concat, which exists and is rarely the best choice:
console.log(first.concat(" ", last)); // Ada Lovelace
// Works, but says less clearly what a template literal says better.
repeat, for when you need the same text several times:
console.log("-".repeat(20)); // --------------------
console.log("ab".repeat(3)); // ababab
console.log("x".repeat(0)); // "" empty, not an error
// Useful for simple output formatting:
const title = "Report";
console.log(title);
console.log("=".repeat(title.length));
// Report
// ======
padStart and padEnd, for lining things up:
console.log("7".padStart(3, "0")); // 007
console.log("42".padStart(3, "0")); // 042
const items = [["Tea", 40], ["Coffee", 120]];
for (const [name, price] of items) {
console.log(name.padEnd(10) + String(price).padStart(5));
}
// Tea 40
// Coffee 120
Use template literals for anything that mixes text and values, and keep + for the simplest possible joins. The reason is not style: the + form silently produces "AdaLovelace" when you forget a space, while the template literal form shows the space right there in the text where your eye expects it.
