Start learning free

LESSON 65 OF 348 · STRINGS I

String Length in TypeScript: The length Property

Lesson Read the full explanation

We can get the length of a string using the .length property like this:

let message = "Hello world";

// Printing the length:
console.log(message.length); // Output: 11

// Changing the message:
message += "!";

// Printing the new length:
console.log(message.length); // Output: 12

Accessing characters from the end:

The length is useful for accessing characters from the end of a string.

Because strings are 0-indexed, the index of the last character is length - 1:

let message = "Hello world";
let length = message.length;

// Printing the last character:
console.log(message[length - 1]); // Output: d

// Printing the second to last character:
console.log(message[length - 2]); // Output: l

In general, if you want the nth last character, you access message[length - n].


Slicing characters from the end:

The length is also useful for slicing some characters from the end of a string:

let message = "Hello world";
let length = message.length;

// Slicing last 4 characters:
let lastChars = message.slice(length - 4);
console.log(lastChars); // Output: orld

// Slicing last 7 characters:
lastChars = message.slice(length - 7);
console.log(lastChars); // Output: o world

In general, if you want the last n characters, you use message.slice(length - n).


Assignment
Follow the Coding Tutorial and let's practice with string length!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    TYPESCRIPT · STRINGS I

    String Length in TypeScript, explained

    Reading the length

    Every string has a length property holding the number of characters in it. It is a property, not a method, so there are no parentheses after it:

    let message = "Hello world";
    console.log(message.length);
    message += "!";
    console.log(message.length);
    
    11
    12
    

    Spaces count as characters, which is why "Hello world" has 11 and not 10. The empty string "" has length 0. After the +=, the variable refers to a new, longer string, so reading length again gives the new value.

    Reaching characters from the end

    Indexes start at 0, so the last character of a string is at index length - 1. The nth character from the end is at length - n:

    let message = "Hello world";
    let length = message.length;
    console.log(message[length - 1]);
    console.log(message[length - 2]);
    
    d
    l
    

    This works for a string of any size, which is the reason to use length instead of typing the number. If the text changes later, the code still finds its last character.

    Slicing from the end

    The length also gives you the starting point for taking the last n characters. Start at length - n and run to the end:

    let message = "Hello world";
    let length = message.length;
    console.log(message.slice(length - 4));
    console.log(message.slice(length - 7));
    
    orld
    o world
    

    Both slice and substring accept a start and an end index, and the end is excluded. If the end is the length of the string, the result runs to the last character, so message.substring(message.length - 5, message.length) and message.substring(message.length - 5) are equivalent.

    What length really counts

    The length is the number of UTF-16 code units, which is the same as the number of characters for ordinary text. Characters outside the basic range, such as many emoji, take two units:

    console.log("héllo".length);
    console.log("😀".length);
    console.log([..."😀"].length);
    
    5
    2
    1
    

    Spreading the string into an array splits it by whole characters instead, so the third line is 1. For the plain English text in this chapter you won't see a difference.

    Length in a loop

    The length is also the boundary of most string loops. This one walks from the last index down to 0 and builds the text backwards:

    const word = "pancakes";
    let reversed = "";
    for (let i = word.length - 1; i >= 0; i--) {
        reversed += word[i];
    }
    console.log(reversed);
    
    sekacnap
    

    The loop starts at word.length - 1, the last valid index, and stops after index 0. For an empty string, the start is -1, so the body never runs and reversed stays empty. Reading length in the loop condition costs almost nothing, so you don't need to save it in a variable first.

    Empty strings

    Whitespace-only strings are not empty either: " " has length 1.

    An empty string has length 0, which makes s.length === 0 the usual test for "no text". The last-character formula needs care here: s[s.length - 1] is s[-1], which is undefined, so check for an empty string first when the input might be empty.

    The exercise

    The starter code declares a message:

    let message: string = "I love pancakes";
    
    1. Print the length: message.length, which is 15.
    2. Print the last character: index message.length - 1, which is 14.
    3. Print the last 5 characters with substring. They start at index message.length - 5 and end at message.length, since substring also excludes its end index.
    let message: string = "I love pancakes";
    console.log(message.length);
    console.log(message[message.length - 1]);
    console.log(message.substring(message.length - 5, message.length));
    

    The output is:

    15
    s
    cakes
    

    Gotchas

    • Off by one. message[message.length] is undefined, because the last valid index is length - 1.
    • Method syntax. message.length() is an error, because length is a number, not a function.
    • Short strings. If a string has fewer than 5 characters, message.length - 5 is negative. in the exercise's form with the length as the end, substring treats the negative start as 0 and returns the whole string. For "abc" that is abc, whereas slice counts a negative start from the end and returns bc.
    • You can't assign to it. Setting message.length = 3 doesn't shorten the string, because strings are immutable.

    Key takeaways

    • s.length is the number of characters, spaces included.
    • The last character is at length - 1, and the nth from the end at length - n.
    • The last n characters start at length - n.
    • length is a property; it needs no parentheses.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free