String Length
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
Algorithm Flow

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
function stringLength(text: string): number {
var count = 0;
while (text.charAt(count) !== '') count++;
return count;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
