When working with JavaScript, you will often need to know how many characters are inside a string. For example, you might want to check how long a username is, validate a password, count the characters in a message, or make sure a user does not enter more text than a form allows.
Fortunately, JavaScript makes this task very simple. You can get the length of a string by using the built-in length property.
In this tutorial, you will learn how to get string length in JavaScript, how the length property works, and how to use it with practical examples. We will also look at some common mistakes beginners should avoid.
Watch the Video Tutorial
If you prefer learning by watching, check out this short video tutorial:
Watch: How to Get String Length in JavaScript
What Is String Length in JavaScript?
A string is a sequence of text characters. It can contain letters, numbers, spaces, and special symbols.
For example:
let message = "Hello World";
In this example, "Hello World" is a string. It contains 11 characters, including the space between the two words.
JavaScript provides a built-in property called length that allows you to find the length of a string.
You do not need to write a separate function or install an additional library. Simply use .length after the string variable.
How to Get String Length in JavaScript
The easiest way to get the length of a string is by using the length property.
Syntax:
string.length;
Here, string represents the variable containing your text, and .length returns its length as a number.
Let’s look at a simple example:
let text = "Hello";
console.log(text.length);
Output:
5
As you can see, the result is 5 because the word "Hello" contains five characters.
The length property counts the characters represented by the string’s UTF-16 code units. For ordinary English text, the result usually matches the number of visible characters.
Example 1: Get the Length of a Simple String
Let’s start with a basic example.
let name = "JavaScript";
let result = name.length;
console.log(result);
Output:
10
In this example:
- We created a variable named
name. - We stored the text
"JavaScript"inside it. - We used
name.lengthto get the string length. - We stored the result in the
resultvariable. - Finally, we displayed the result using
console.log().
The output is 10 because the word JavaScript contains ten letters.
Example 2: Get the Length of a String With Spaces
One important thing to remember is that JavaScript also counts spaces when calculating string length.
For example:
let message = "Hello World";
console.log(message.length);
Output:
11
Why is the result 11?
The string contains:
Hello= 5 characters- Space = 1 character
World= 5 characters
Total = 11 characters.
This is useful when checking the length of full names, sentences, addresses, or other text entered by users.
Example 3: Get the Length of an Empty String
What happens if a string does not contain any text?
Let’s see:
let text = "";
console.log(text.length);
Output:
0
An empty string has a length of zero because it contains no characters.
This can be helpful when checking whether a user has entered anything into a text field.
For example:
let username = "";
if (username.length === 0) {
console.log("Please enter your username.");
}
Output:
Please enter your username.
The condition checks whether the username has a length of zero. If it does, JavaScript displays the message.
You can also use username === "" for a direct empty-string check.
Example 4: Get String Length From User Input
The length property is especially useful when working with forms.
Imagine you are building a registration form and want to check how many characters a user has entered.
Here is a simple example:
<input type="text" id="username" placeholder="Enter your name">
<button onclick="checkLength()">Check Length</button>
<p id="result"></p>
<script>
function checkLength() {
let username = document.getElementById("username").value;
let length = username.length;
document.getElementById("result").textContent =
"Your name contains " + length + " characters.";
}
</script>
In this example, we use JavaScript to get the value entered in the input field.
The .length property calculates the length of that value, and the result appears inside the paragraph element.
This is a simple way to combine HTML and JavaScript to create interactive web pages.
Example 5: Check the Minimum String Length
Sometimes, you may want to make sure that a user enters a minimum number of characters.
For example, a username might need to contain at least five characters.
You can use the length property together with an if...else statement.
let username = "John";
if (username.length >= 5) {
console.log("Username is valid.");
} else {
console.log("Username must contain at least 5 characters.");
}
Output:
Username must contain at least 5 characters.
The username "John" contains only four characters, so the condition is false.
JavaScript executes the else block and displays the message.
If you change the username to "John123", the condition becomes true.
This technique is commonly used when creating registration forms and checking user input.
Example 6: Check the Maximum String Length
You can also use .length to prevent users from entering too many characters.
For example, imagine a form where a message must contain no more than 20 characters.
let message = "Hello, welcome to JavaScript!";
if (message.length <= 20) {
console.log("Your message is accepted.");
} else {
console.log("Your message is too long.");
}
Output:
Your message is too long.
The condition checks whether the message contains 20 characters or fewer.
If the string is longer than 20 characters, JavaScript displays the warning.
This approach is useful for short descriptions, usernames, titles, and message fields.
Example 7: Count Characters Using a For Loop
You do not normally need a loop to get a string’s length because .length already does the job.
However, understanding how it works with a for loop is useful when learning JavaScript.
let text = "Hello";
for (let i = 0; i < text.length; i++) {
console.log(text[i]);
}
Output:
H
e
l
l
o
Here, text.length tells the loop how many times it should run.
The loop starts at index 0 and continues while i is smaller than the string length.
Remember that JavaScript string indexes start at zero. That means the first character is at index 0, while the last character is at index text.length - 1.
Does JavaScript Count Spaces and Special Characters?
Yes. The length property includes spaces, punctuation marks, and most ordinary symbols in its count.
For example:
let text = "Hi! How are you?";
console.log(text.length);
Output:
16
The spaces, exclamation mark, and question mark are all included in the result.
This is important when calculating the length of messages or validating text entered by users.
Important: How JavaScript Counts Emojis
There is one detail worth knowing when working with JavaScript strings.
The length property does not always return the number of visible characters. It counts UTF-16 code units.
For example:
let emoji = "😊";
console.log(emoji.length);
Output:
2
You might expect the result to be 1 because there is only one visible emoji. However, this emoji is represented using two UTF-16 code units, so JavaScript returns 2.
If you want to count Unicode code points instead, you can use the spread syntax:
let emoji = "😊";
console.log([...emoji].length);
Output:
1
For more complex symbols made from multiple Unicode code points, even this method may not match the number of visible characters. In those cases, JavaScript provides Intl.Segmenter, which can count grapheme clusters.
For example:
let text = "Hello 😊";
let segmenter = new Intl.Segmenter("en", {
granularity: "grapheme"
});
let count = [...segmenter.segment(text)].length;
console.log(count);
Output:
7
This counts the visible character groups in the text, including the emoji as one grapheme.
For most beginner projects involving ordinary text, .length is exactly the property you need. Just remember the difference when working with emojis and complex Unicode text.
Common Mistakes When Using String Length in JavaScript
Although the length property is easy to use, beginners sometimes make a few mistakes.
1. Using Parentheses After Length
The length property is not a function. You should not add parentheses after it.
Incorrect:
let text = "Hello";
console.log(text.length());
Correct:
console.log(text.length);
Remember: use .length, not .length().
2. Forgetting That Spaces Are Counted
Consider this example:
let name = "John Smith";
console.log(name.length);
The result is 10, not 9, because the space between the first and last name is included.
3. Confusing String Length With the Last Index
JavaScript strings use zero-based indexing.
For example:
let text = "Hello";
console.log(text.length); // 5
console.log(text[4]); // o
The string length is five, but the last character is at index four.
If you want to access the last character of a string, you can use:
console.log(text[text.length - 1]);
Output:
o
4. Trying to Change the Length Property
The length property of a string is read-only.
For example:
let text = "JavaScript";
text.length = 5;
console.log(text);
console.log(text.length);
The string remains "JavaScript", and its length remains 10.
If you want a shorter string, you can create a new one using a method such as slice():
let text = "JavaScript";
let shortText = text.slice(0, 5);
console.log(shortText);
Output:
JavaS
Difference Between String Length and String Size
It is also useful to understand that string length and string storage size are not the same thing.
The .length property returns the number of UTF-16 code units in a string. It does not tell you exactly how many bytes the string occupies in memory.
For example:
let text = "Hello";
console.log(text.length);
The result is 5, but this does not mean the string always takes exactly five bytes in memory.
JavaScript engines manage string storage internally, so the actual memory usage can depend on the engine and the string’s contents.
Frequently Asked Questions
1. How do I get the length of a string in JavaScript?
Use the built-in .length property.
let text = "Hello World";
console.log(text.length);
The result is 11, including the space.
2. Is length a method or a property in JavaScript?
length is a property, not a method. You should write text.length, without parentheses.
3. Does JavaScript string length count spaces?
Yes. Spaces are included when JavaScript calculates the length of a string.
4. What is the length of an empty string?
The length of an empty string is 0.
let text = "";
console.log(text.length);
5. How can I get the last character of a string?
You can use text[text.length - 1].
let text = "JavaScript";
console.log(text[text.length - 1]);
The output is t.
6. Can I use string length to validate a password?
Yes. You can use .length to check whether a password meets a minimum or maximum character count.
However, password length alone does not make a password secure. A real password validation system should also follow appropriate security practices.
Conclusion
Getting the length of a string in JavaScript is simple. You only need to use the built-in length property.
Whether you are checking a username, validating a password, counting a message, or working with user input, .length is one of the most useful JavaScript properties to understand.
Here is the basic syntax one more time:
let text = "Hello World";
console.log(text.length);
Output:
11
Keep practicing these examples and try using the length property in your own projects. Once you understand how it works, you will find many situations where it makes your JavaScript code easier to write.
If you want to continue learning, explore more JavaScript tutorials on strings, variables, conditions, and functions.
Ready to become a better coder? Don’t miss this tutorial! Animation Direction in CSS
