The string length function in JavaScript is the .length property, used as myString.length. It returns the number of UTF-16 code units in the string, which for most everyday text equals the number of characters, but for emoji or certain accented letters it can differ.
How .length works under the hood
JavaScript strings are stored as sequences of 16-bit values called UTF-16 code units. The .length property counts these code units, not necessarily the visual characters or graphemes you see on screen. For example, the string "hello" has length 5 because each letter is one code unit. But "π" (a simple smiley emoji) has length 2 because that emoji is encoded as a surrogate pair β two code units.
Here are a few concrete examples you can try in your browser console:
"abc".lengthβ 3"".lengthβ 0 (empty string)"Γ©".lengthβ 1 (precomposed e with acute accent)"eΜ".lengthβ 2 (e followed by combining acute accent)"π¨βπ©βπ§βπ¦".lengthβ 11 (family emoji, made of multiple code points)
This distinction matters when you validate input lengths, truncate text, or count characters for a UI. If you need the number of visible characters (grapheme clusters), you must use a different approach.
Using .length in real code
The .length property is read-only and available on every string. You can access it directly on a string literal or a variable. It is a property, not a function, so you do not call it with parentheses.
Common use cases include:
- Checking if a user input is empty:
if (input.length === 0) - Limiting input length:
if (text.length > 140) { // reject } - Looping through characters:
for (let i = 0; i < str.length; i++) - Getting the last character:
str[str.length - 1]
Remember that length is a property, so you cannot assign to it (it has no effect in non-strict mode and throws in strict mode).
Counting characters vs. code points
If you need the number of Unicode code points (which includes emoji as single entities), use the Array.from() method or the spread operator:
const emoji = "π";
console.log(emoji.length); // 2
console.log(Array.from(emoji).length); // 1
console.log([...emoji].length); // 1
For grapheme clusters (what a user perceives as a single character, like the family emoji or a letter with a combining mark), you need the Intl.Segmenter API, which is available in modern browsers and Node.js:
const segmenter = new Intl.Segmenter('en', { granularity: 'grapheme' });
const graphemes = Array.from(segmenter.segment('π¨βπ©βπ§βπ¦'));
console.log(graphemes.length); // 1
This is the most accurate way to count visible characters, but it is slower and not supported in older environments. For most validation purposes, .length is sufficient.
Common pitfalls and misconceptions
One frequent mistake is assuming .length counts characters. As shown, that is false for astral symbols (emoji, some rare scripts) and combining sequences. Another pitfall is using length to check if a string is null or undefined β it will throw an error. Always check for null/undefined first:
if (myString && myString.length > 0) { /* safe */ }
Also, note that length is not a function, so calling myString.length() will throw a TypeError. Finally, be aware that strings are immutable; length never changes after creation.
Performance considerations
For most applications, accessing .length is O(1) β the engine stores the length internally. It is extremely fast and safe to use in loops. However, if you are iterating over a very large string and using Array.from() or Intl.Segmenter, that will be slower because it creates an array or performs segmentation. Use these only when you truly need code point or grapheme counts.
If you need to truncate a string to a certain number of characters (for example, a tweet), be careful with emoji: slicing by .length may cut a surrogate pair in half, producing a broken character. Use Array.from() or a loop that respects code points.
Alternatives to .length
There is no built-in function named strlen in JavaScript (unlike PHP or C). The only native way is the .length property. However, you can create your own helper functions for specific needs:
- Code point count:
const codePointLength = str => Array.from(str).length; - Grapheme count:
const graphemeLength = str => new Intl.Segmenter().segment(str).length;(note: need to iterate over the segmenter's iterator) - Byte length (UTF-8):
new TextEncoder().encode(str).lengthβ useful for sending data over networks.
For most web development, .length is the right tool. Only reach for alternatives when you are handling international text or emoji-heavy content.
Frequently Asked Questions
Why does 'π'.length return 2?
Because JavaScript uses UTF-16 encoding, and emoji like π are represented as a pair of 16-bit code units (a surrogate pair). The .length property counts code units, not visual characters.
How do I count the number of characters in a string including emoji correctly?
Use Array.from(str).length to count code points, or Intl.Segmenter to count grapheme clusters. For most cases, Array.from is enough, but for complex emoji like family emojis, use Intl.Segmenter.
Is .length a function or a property?
It is a property. You access it without parentheses: str.length. Calling str.length() will throw a TypeError.
Can I change the length of a string?
No, strings are immutable. You cannot modify .length directly. You can create a new string with a different length using methods like slice, substring, or concatenation.
Does .length count spaces and punctuation?
Yes, every character, including spaces, punctuation, tabs, and newlines, counts as one code unit (or more if they are astral). For example, "a b".length is 3.
What is the difference between .length and .size for strings?
Strings do not have a .size property. .size is used on Sets and Maps. For strings, only .length is available.
Related
- Reverse a String in Java: Methods and Examples
- Split a String in C++: Methods and Examples
- String to Int in C++: Safe Conversion Methods
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Conditional Formatting Formula in Excel: How to Use ItIn Excel, a conditional-formatting equation is a formula that returns TRUE or FALSE; Excel applies the chosen format…
- Excel Ordered List Formula: Number Rows AutomaticallyIn Excel for Microsoft 365, enter =ROWS($A$2:A2) in B2 when your list items are in A2:A20, then fill…
- Excel Formula Bar: What It Shows and How to Use ItIn Excel, the Formula Bar is the field above the worksheet that shows the contents of the selected…
- Calculating NPV and IRR in Excel: Formulas and StepsTo calculate NPV in Excel, discount the future cash flows with NPV and add the initial cash flow…
- Change Caps Lock to Lowercase in Excel with a FormulaTo change text that is already in all caps to lowercase in Excel, enter =LOWER(A2) in a blank…
- How to Capitalize Every Word in Excel with a FormulaTo capitalize every word in Excel, enter =IF(A2="","",PROPER(A2)) in an empty column beside the text in A2, then…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.