In JavaScript, get a string’s length with its .length property—not a function call: const count = text.length;. The value is the number of UTF-16 code units in the string, so some visible symbols, including many emoji, count as two or more.
How the length Property Works
A JavaScript string is a sequence of UTF-16 code units. Its length property reports how many of those units it contains. The property belongs to the string value, and you read it with dot notation. It does not take parentheses or an argument.
const message = 'Hello';
console.log(message.length); // 5
That result is a number. It is useful for checking whether a string is empty, measuring it according to JavaScript’s built-in convention, and deciding where to start or stop many string operations. JavaScript strings are immutable, so reading length does not change the string.
Although people often call length a “function,” it is a property. These forms are different:
text.lengthreads the length and returns a number.text.length()attempts to call that number as a function and normally throws aTypeError.
Basic Examples: Empty Strings, Spaces, and Variables
The length of an empty string is zero. A space, tab, or newline is still part of a string and contributes to its length. This matters when inspecting user input: a value that looks blank may contain whitespace.
const empty = '';
const spaces = ' ';
const greeting = 'Hi there';
console.log(empty.length); // 0
console.log(spaces.length); // 3
console.log(greeting.length); // 8
You can use the property directly in a condition. For example, if (name.length === 0) checks whether name contains no code units. It does not treat a whitespace-only value as empty. If the goal is to reject input made only of ordinary leading or trailing whitespace, check name.trim().length === 0 instead. trim() returns a new string with whitespace removed from its ends; it does not alter the original.
The same property works on a string literal, a variable, or a value returned by a string operation:
console.log('JavaScript'.length); // 10
console.log(' ok '.trim().length); // 2
Why Emoji Can Have a Length of Two or More
The most important detail is that length counts UTF-16 code units, not user-perceived characters. Many common letters fit in one code unit, which is why ordinary English examples can make the property seem like a character counter. Unicode also includes code points that require a pair of UTF-16 code units. A symbol represented by such a pair contributes two to length.
console.log('A'.length); // 1
console.log('😀'.length); // 2
Some emoji sequences contain multiple code points joined together or combined with modifiers. A family emoji, for example, may contain several people symbols and zero-width joiners. Skin-tone variants can also add code points. Those sequences may look like one symbol on screen while their JavaScript string length is several code units. The exact count depends on the sequence, so do not assume every emoji has length two.
This distinction is also relevant when using numeric indexes. For a string containing a supplementary Unicode symbol, bracket access can return one half of its UTF-16 surrogate pair rather than the whole displayed symbol. For example, '😀'[0] returns the first code unit as a one-unit string. That result may look like an unexpected or broken character when displayed by itself.
Code Units, Code Points, and Visible Characters
There are several sensible ways to count a string, and they answer different questions:
- UTF-16 code units: what
string.lengthcounts. This is the built-in JavaScript length and the unit used by many string indexing operations. - Unicode code points: individual Unicode values. A surrogate pair represents one code point, even though it uses two code units.
- Grapheme clusters: units that approximate what a person perceives as a single character. A letter plus a combining accent, or a joined emoji sequence, can form one grapheme cluster while containing multiple code points.
If you specifically need a code-point count, the string iterator handles a valid surrogate pair as one item. Spreading the string into an array and reading that array’s length is one option:
const text = 'A😀';
console.log([...text].length); // 2 code points
This does not count every visible character as one. A letter followed by a combining accent can still be two code points, and a joined emoji can still be several. The spread operation also creates an array, so it uses additional memory and takes work proportional to the string’s size. It is appropriate when code-point counting is the intended requirement, not as a universal replacement for .length.
For a count closer to what a person sees as characters, use Intl.Segmenter with grapheme granularity in environments that support it:
const segmenter = new Intl.Segmenter(undefined, {
granularity: 'grapheme'
});
const visibleUnits = [...segmenter.segment('A😀')].length;
console.log(visibleUnits); // 2 grapheme clusters
Grapheme segmentation follows Unicode text-segmentation rules; it is not a promise that every font or interface will display each cluster identically. If your application needs to count visible characters, check that the JavaScript environments you support provide Intl.Segmenter, and define clearly what your product means by a character.
Using Length for Validation and Limits
A common use is to enforce a minimum or maximum input length. The comparison itself is simple:
if (password.length < 12) {
console.log('Use at least 12 UTF-16 code units.');
}
However, a product requirement that says “12 characters” may mean code units, code points, grapheme clusters, or even a byte limit after encoding. These are not interchangeable. Choose the measure that matches the requirement and explain it in the interface. For instance, a visual character limit for a text field may be more intuitive when calculated in grapheme clusters, while a particular API or storage format may specify a byte limit.
Client-side checks are useful for immediate feedback, but they should not be the only enforcement when data is submitted to a server. The server should apply the same defined rule because clients can be modified or bypassed. Also, a JavaScript string-length limit does not automatically tell you how many bytes the value will occupy when encoded as UTF-8 or stored elsewhere.
For whitespace-sensitive checks, decide whether whitespace is allowed and whether it should count. value.trim().length checks the length after trimming the ends, whereas value.length includes them. Do not trim automatically if spaces are meaningful in the data, such as in a passphrase or a deliberately formatted text field.
Other Values and Common Mistakes
The length property is not a general-purpose way to measure every JavaScript value. Arrays also have a length property, but it reports the array’s highest index plus one, not the number of defined elements in every case. A sparse array can contain empty slots, so its length can be larger than the number of values it actually stores. Other values may not have a useful length property at all.
In particular, null and undefined do not have a length property. Trying to read value.length when value is either one will throw an error. If a function accepts values that may not be strings, validate or convert them deliberately rather than assuming they have a string length.
function getStringLength(value) {
if (typeof value !== 'string') {
throw new TypeError('Expected a string');
}
return value.length;
}
Conversion can be appropriate when the input is meant to be displayed as text, but it changes the question: String(value).length measures the length of the converted string. For example, converting a number produces its textual representation, not a measure of the number itself. Be cautious with implicit conversions, since they can hide unexpected input types.
You may also encounter new String('text'), which creates a string object rather than a primitive string. It has a length property too, but wrapping strings with new String is usually unnecessary and can create confusing type checks. Prefer a string primitive such as 'text' or String(value) when conversion is intended.
Performance and Choosing the Right Count
For normal application code, read .length directly when you need JavaScript’s standard string length. The language specifies the resulting count, while the exact internal representation and optimization strategy are implementation details. You generally do not need to build a separate counter just to avoid accessing the property.
By contrast, converting a string to an array with spread or calling a segmentation routine must process its contents to produce the requested units. Use those approaches because you need code points or grapheme clusters, not because they are more correct for every situation. When a requirement mentions “characters,” ask what should happen for emoji, combining marks, and joined sequences before choosing a counting method.
A practical decision guide is:
- Use
text.lengthfor the built-in UTF-16 length, indexing-related work, and rules explicitly defined in code units. - Use
[...text].lengthwhen the requirement is to count Unicode code points. - Use
Intl.Segmenterwithgranularity: 'grapheme'when you need a count that better matches user-perceived characters. - Use a byte-counting method based on the required encoding when a protocol or storage limit is expressed in bytes.
Frequently Asked Questions
Is string length a function in JavaScript?
No. It is a property. Write text.length, not text.length(). Calling it with parentheses attempts to call the returned number as a function.
Why does an emoji have a length of 2?
Many emoji use a Unicode code point represented in UTF-16 by a surrogate pair. JavaScript counts the pair as two code units. More elaborate emoji sequences can have still higher lengths.
How do I count characters instead of UTF-16 units?
First decide what “character” means. Use [...text].length for code points, or Intl.Segmenter with grapheme granularity for clusters that more closely match visible characters.
Does length count spaces?
Yes. Spaces, tabs, and newlines inside a string count. To ignore whitespace at the beginning and end, measure text.trim().length; that does not remove whitespace in the middle.
What is the length of an empty string?
An empty string, written '', has length 0. A string containing one or more spaces is not empty and has a positive length.
Can I use length on null or undefined?
No. Reading null.length or undefined.length throws an error. Check the value’s type or handle missing values before accessing the property.
Related
- How to Split an Array in Java: Safe Ways to Do It Cleanly
- Balance of Payments Notes: Accounts, Examples and Meaning
- Java split(): How It Handles Delimiters and Limits
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Vertex Debt Snowball Spreadsheet: How to Use ItIf by “Vertex” you mean Vertex42, the relevant resource is its Debt Reduction Calculator spreadsheet; check Vertex42’s official…
- UK Date Format in Google Sheets: Set Dates CorrectlyTo get UK dates in Google Sheets, set the spreadsheet locale to United Kingdom, then format the date…
- Excel Table Drop-Down List: Set Up a Dynamic ListTo add a drop-down list to an Excel table, select the cells where users will choose an item,…
- Build an Enum from Excel Data: Practical Guide and ChecksYes. You can use Excel as the source for an enum by keeping each permitted name and its…
- How to Share a Team Calendar in Outlook with PermissionsTo share a team calendar in Outlook, open Calendar, select the calendar you want coworkers to use, and…
- How to Properly Archive Emails in Microsoft OutlookTo archive email in Outlook, select the message and choose Archive on the toolbar; Outlook moves it to…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.