Code Logo

String Length

Published at24 Jul 2026
TypeScript String Handling Easy 2 views
Like0

Write a TypeScript function that returns the length of a string without using the built-in .length property. Count the characters manually with a loop.

Initialize a counter to 0. Use a while loop that increments the counter while checking if the character at the current index exists using charAt(). Alternatively, use a for loop that increments the counter until charAt(i) returns an empty string.

Edge cases include empty strings (return 0) and strings with special characters or spaces.

Implementing string length manually demonstrates that properties and methods are abstractions over underlying computation. The charAt() method returns an empty string when accessing an index beyond the string length, making it suitable for loop termination checking.

The charAt() method is a standard String prototype method that returns the character at a specified index. When the index is out of range, it returns an empty string rather than undefined, making it safe for loop termination checks.

This manual length calculation demonstrates that built-in properties like .length are not magic but are computed values. Understanding what happens behind the scenes is important for developing a deeper understanding of programming languages.

Example Input & Output

Example 1
Input
"a"
Output
1
Example 2
Input
"Hello"
Output
5
Example 3
Input
" "
Output
2
Example 4
Input
""
Output
0
Example 5
Input
"TypeScript"
Output
10

Algorithm Flow

Recommendation Algorithm Flow for String Length
Recommendation Algorithm Flow for String Length

Solution Approach

Initialize count = 0. Use a while loop: while (text.charAt(count) !== '') count++. When charAt returns '' (empty string for out-of-bounds), the loop stops and count equals the string length.

Alternatively, use a for loop with an empty body that increments count.

The time complexity is O(n). Space complexity is O(1).

Best Answers

typescript - Approach 1
function stringLength(text: string): number {
    var count = 0;
    while (text.charAt(count) !== '') count++;
    return count;
}