DevPath · Learn to code ESPTEN

Text strings

Length and access by index

Looking inside a string

How many letters does a name have? What's its initial? To answer that you need two things: to measure the string and to read a character by its position. Let's do it.

The length property

Every string knows how many characters it has thanks to .length:

const word = "JavaScript";
console.log(word.length); // 10

Spaces also count as characters.

Access by index

A string is like a row of numbered slots.

⚠️ CLASSIC TRAP: the numbering starts at 0, not 1. The first character lives at index 0. Almost everyone stumbles over this at first, so burn it in: to reach the first one, you ask for 0.

 J  a  v  a  S  c  r  i  p  t
 0  1  2  3  4  5  6  7  8  9

To read a character you use brackets with its position:

const word = "JavaScript";
console.log(word[0]); // "J"
console.log(word[4]); // "S"

The last character

Since we count from 0, the last character is not at length, but one slot earlier: at length - 1. If a word has 4 letters, its last one is at index 3.

const word = "Hola";
const last = word[word.length - 1];
console.log(last); // "a"

If you request an index that does not exist (for example word[100]), you get undefined instead of an error.

Examples

length and first character

const city = "Madrid";
console.log("Length:", city.length);
console.log("Initial:", city[0]);

Get the last character

const word = "JavaScript";
console.log("Last:", word[word.length - 1]);
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Creating strings and template literalsMethods to transform text →