Start learning free

LESSON 62 OF 348 · STRINGS I

Accessing Characters in TypeScript: Bracket Notation

Lesson Read the full explanation

Each character in a string has a numbered position known as its index. We access a character by referring to its index number.

Strings use zero-based indexing, so the first character in a string has an index of 0, the second character has an index of 1, etc.

We’re using bracket notation ([]) with the index after the name of the string to access the character:

let message = "Hello world!";

console.log(message[0]); // Output: H
console.log(message[1]); // Output: e
console.log(message[6]); // Output: w

Whitespaces have indices:

Note that every character inside the quotes (including whitespaces) is part of the string and has its own index. For example, in string "Hello world!", the whitespace is placed on index 5.

However, if you run this code:

let message = "Hello world!";

console.log(message[5]);

you would see that nothing was printed to the console, not a whitespace and not even a new line as console.log() always does.

This is because console.log() refuses to print strings consisting only of whitespaces for some reason. It just disregards them.

But don't get tricked by this, that whitespace exists and it's on index 5. You can see that clearly when you run this code:

let message = "Hello world!";

console.log(message[4] + message[5] + message[6]);

the output is:

o w

Assignment
Follow the Coding Tutorial and let's access some characters!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    TYPESCRIPT · STRINGS I

    Accessing Characters in TypeScript, explained

    Indexes and bracket notation

    Every character in a string has a numbered position called its index. Counting starts at 0, so the first character has index 0, the second has index 1, and so on. To read a character, write the string, then the index in square brackets:

    let message = "Hello world!";
    console.log(message[0]);
    console.log(message[1]);
    console.log(message[6]);
    
    H
    e
    w
    

    In "Hello world!" the letters H, e, l, l, o take indexes 0 to 4. The space is at index 5, and w is at index 6. The string has 12 characters, so the last valid index is 11.

    What you get back

    Indexing a string returns another string, one character long. TypeScript has no separate character type:

    let fruit: string = "Avocado";
    console.log(typeof fruit[0]);
    console.log(fruit[0].length);
    
    string
    1
    

    This is why + on two characters joins them instead of adding numbers: "a" + "b" is "ab".

    Spaces have indexes too

    Every character inside the quotes counts, including spaces. Printing the character at index 5 of "Hello world!" shows what looks like an empty line. It is not empty: console.log printed a single space followed by the usual line break, and a space is invisible on screen. Wrapping the value in other text makes it visible:

    let message = "Hello world!";
    console.log("[" + message[5] + "]");
    console.log(message[4] + message[5] + message[6]);
    
    [ ]
    o w
    

    Going past the ends

    An index that doesn't exist doesn't cause an error. The result is undefined:

    let fruit: string = "Avocado";
    console.log(fruit[10]);
    console.log(fruit[-1]);
    
    undefined
    undefined
    

    Negative numbers do not count from the end, as they do in some languages. fruit[-1] looks for a property named -1, which doesn't exist. The compiler assumes the result is a string, so it doesn't warn you; the types are erased at run time and cannot protect you here. Check the index yourself when it comes from a calculation.

    Visiting every character

    Because the valid indexes run from 0 to length - 1, a loop over a string uses the length as its stopping point:

    let fruit: string = "Avocado";
    for (let i = 0; i < fruit.length; i++) {
        console.log(i, fruit[i]);
    }
    
    0 A
    1 v
    2 o
    3 c
    4 a
    5 d
    6 o
    

    The condition is i < fruit.length, not i <= fruit.length. The second form would also try index 7 and read undefined. The method charAt is an older alternative to brackets: fruit.charAt(0) is "A", and for an index that doesn't exist it returns an empty string instead of undefined.

    Reaching the last character

    The last index is always the length minus 1, because indexes start at 0. The length property gives the number of characters, so fruit[fruit.length - 1] reaches the last character of a string of any size. For "Avocado", the length is 7 and the last index is 6.

    The string method at does accept negative positions: fruit.at(-1) is the last character. It is a convenient alternative, and the lesson uses the explicit length - 1 form.

    An index can come from a calculation, but it must be a whole number. For "Avocado", fruit[Math.floor(fruit.length / 2)] picks the middle character: 7 divided by 2 is 3.5, rounded down to 3, and fruit[3] is "c". Without the rounding, fruit[3.5] is undefined, because no property has that name. Keep that in mind whenever the index comes from a division.

    The exercise

    The starter code declares fruit:

    let fruit: string = "Avocado";
    
    1. Print the first character with index 0.
    2. Print the last character with fruit.length - 1 as the index.
    let fruit: string = "Avocado";
    console.log(fruit[0]);
    console.log(fruit[fruit.length - 1]);
    

    The output is:

    A
    o
    

    Gotchas

    • Off by one. fruit[fruit.length] is undefined, because the last valid index is one less than the length.
    • The empty string. ""[0] is undefined and "".length - 1 is -1, so the last-character formula returns undefined for an empty string.
    • Letters, not symbols. Indexes count UTF-16 code units. Most text works as expected, but an emoji like "😀" has length 2.
    • Reading only. You can read fruit[0], but you can't assign to it. The next lessons explain why.

    Key takeaways

    • Indexes start at 0, and spaces count.
    • string[i] returns a one-character string.
    • A missing index gives undefined, not an error.
    • The last character is at length - 1.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free