The length property tells you how many UTF-16 code units a string holds—essential for validation, loops, and truncation. This tutorial covers syntax, five worked examples, emoji gotchas, and best practices every beginner should know.
01
Syntax
str.length
02
Count
Letters & symbols
03
Validate
Min/max checks
04
Loop
Index 0 to n−1
05
Read-only
Cannot assign
06
Emoji
UTF-16 units
Fundamentals
Introduction
Every string in JavaScript carries a built-in length property. It answers one of the most common questions in programming: how big is this text? Whether you are validating a password, building a tweet counter, or looping through characters, length is usually the first tool you reach for.
In this guide you will learn how length works, how to use it in real validation and UI code, and what to watch out for with emoji and other multibyte characters.
Concept
Understanding the length Property
length returns a non-negative integer representing the number of UTF-16 code units in the string. For everyday ASCII and Latin text, each visible character typically counts as one unit. Spaces, tabs, newlines, digits, and punctuation all count too.
The property is read-only. Strings are immutable in JavaScript, so assigning to length has no effect (and is ignored in strict mode or silently fails in sloppy mode).
💡
Beginner Tip
An empty string "" has length of 0. Always check for empty input before assuming length means “has content”—a string of only spaces still has a non-zero length.
Usage
How to Use the length Property
Access length directly on any string primitive or String object. It is most often used in conditionals to enforce size rules:
JavaScript
const password = "mypassword";
if (password.length >= 8) {
console.log("Password length is sufficient.");
} else {
console.log("Password is too short.");
}
You can also use length as the upper bound in a for loop to visit each index from 0 to length - 1, or compare it against a maximum before truncating with slice.
Foundation
📝 Syntax
JavaScript
string.length
Return value
A non-negative integer (0 or greater).
Never throws for valid strings.
Common patterns
text.length === 0 — check for empty string.
text.length >= min && text.length <= max — range validation.
for (let i = 0; i < text.length; i++) — index-based iteration.
text.length > limit ? text.slice(0, limit) + "…" : text — truncate with ellipsis.
Cheat Sheet
⚡ Quick Reference
Goal
Code
Get character count
str.length
Empty check
str.length === 0
Minimum length
str.length >= 8
Last valid index
str.length - 1
Writable?
No (read-only)
Emoji caveat
Counts UTF-16 units, not graphemes
Compare
📋 length vs Visible Characters
For most English text they match. Emoji and some Unicode symbols need a different approach when users care about “character count.”
ASCII text
"Hi".length
Returns 2
Emoji
"💖".length
Returns 2 (surrogate pair)
Spread
[..."💖"].length
Better for many emoji
Segmenter
Intl.Segmenter
Most accurate (modern)
Hands-On
Examples Gallery
Open DevTools Console (F12) and paste each snippet, or use the Try-it links. Examples progress from basic counting to validation, loops, emoji, and a live counter.
📚 Getting Started
Read length on everyday strings.
Example 1 — Measure a Simple String
Count the characters in a greeting, including the comma and space.
Each UTF-16 code unit in the string adds 1 to length. Punctuation and whitespace are not special—they count just like letters.
📈 Practical Patterns
Validation, iteration, Unicode, and UI counters.
Example 2 — Password Length Validation
Reject passwords shorter than eight characters before saving.
JavaScript
function validatePassword(password) {
if (password.length < 8) {
return "Password must be at least 8 characters.";
}
if (password.length > 128) {
return "Password is too long.";
}
return "Password accepted.";
}
console.log(validatePassword("short")); // too short
console.log(validatePassword("mypassword")); // accepted
Valid indexes run from 0 to length - 1. Walking backward from the last index is a classic pattern for reversing text without calling split().reverse().join().
Example 4 — The Emoji Length Surprise
Some visible characters occupy two UTF-16 code units, so length can over-count.
JavaScript
const heart = "💖";
const flag = "🇮🇳";
console.log(heart.length); // 2 (not 1!)
console.log([...heart].length); // 1 (spread by code point)
console.log(flag.length); // 4 (regional indicator pair)
// Modern alternative for user-visible counts:
const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
const graphemes = [...segmenter.segment(heart)].length;
console.log(graphemes); // 1
JavaScript strings are UTF-16 internally. Emoji and flag sequences often use surrogate pairs or multiple code points. For tweet counters or form limits shown to users, prefer Intl.Segmenter or spread syntax when emoji are expected.
Example 5 — Live Character Counter
Update a label as the user types in a textarea—a common UI pattern powered by .length.
The input event fires on every change to the textarea. Reading textarea.value.length gives an instant count without scanning the DOM character by character.
Applications
🚀 Common Use Cases
Input validation — enforce minimum and maximum field sizes in forms.
Substring extraction — know valid index bounds before calling slice or substring.
Looping over characters — drive index-based for loops from 0 to length - 1.
Truncating strings — shorten previews that exceed a display limit.
Empty checks — guard against blank user input with length === 0.
Progress indicators — show “280 / 280” style counters in social or chat apps.
Watch Out
Important Considerations
Multibyte characters — length counts UTF-16 code units, not user-visible graphemes. Emoji like "💖" report 2.
Whitespace — spaces, tabs, and newline characters all increase length. Trim first if you care about meaningful content only.
Immutable property — assigning str.length = 5 does not shorten the string. Create a new string instead.
Not byte size — length is not the storage size in bytes; encoding (UTF-8, UTF-16) affects memory differently.
Array.length differs — arrays also have length, but it tracks elements and can be writable in some edge cases; string length is always read-only.
🧠 How JavaScript Computes length
1
Store as UTF-16
The engine keeps string data as a sequence of 16-bit code units internally.
Encoding
2
Count units
Reading .length returns the total number of those code units—O(1) in modern engines.
Fast read
3
Expose read-only
The property cannot be assigned. Changing text requires creating a new string value.
Immutable
4
📏
Use in logic
Compare, loop, validate, or truncate based on the returned integer.
Important
📝 Notes
Primitives auto-box when you access .length—no need for new String().
trim().length ignores leading/trailing whitespace if you only care about trimmed content.
For international apps, test counters with emoji and combining characters from your target locales.
String.prototype.length on the prototype itself is unrelated to instance length.
Template literals and concatenation produce strings that support length immediately.
When in doubt for user-facing limits, document whether the limit is code units or visible characters.
Compatibility
Browser & Runtime Support
The String.length property is a core JavaScript feature available since the earliest editions of the language.
✓ Baseline · ES1+
String.length
Supported in every browser and all Node.js versions. Intl.Segmenter for grapheme counts requires modern browsers (Chrome 87+, Firefox 125+, Safari 14.1+).
99%Universal API
Google ChromeSupported · Desktop & Mobile
Full support
Mozilla FirefoxSupported · Desktop & Mobile
Full support
Apple SafariSupported · macOS & iOS
Full support
Microsoft EdgeSupported · Chromium
Full support
Internet ExplorerNo native support · Use a polyfill
Polyfill
OperaSupported · Modern versions
Full support
Samsung InternetSupported · Android
Full support
BunSupported · JavaScript runtime
Supported
DenoSupported · JavaScript runtime
Supported
Node.jsSupported · Server runtime
Supported
Android WebViewSupported · Modern WebView
Full support
String.lengthExcellent
Bottom line: Safe everywhere for basic counting. Use Intl.Segmenter when emoji-accurate user limits matter and you can target modern browsers.
Wrap Up
Conclusion
The length property is one of the simplest and most useful tools in JavaScript string handling. It powers validation, loops, truncation, and live counters with a single property read.
Remember that it counts UTF-16 code units, not always visible characters. For emoji-heavy apps, combine length with Intl.Segmenter or spread syntax when user expectations differ from internal encoding.
Trim whitespace when only meaningful content counts
Use Intl.Segmenter for emoji-aware UI limits
Combine with slice for safe truncation
❌ Don’t
Try to assign a new value to length
Assume length equals visible character count for all Unicode
Confuse string length with byte size or array semantics
Skip empty-string checks after trimming
Rely on length alone for password strength
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about String.length
Your foundation for counting and validating text in JavaScript.
5
Core concepts
📝01
Syntax
str.length
API
🔢02
Empty
"" → 0.
Edge case
🔒03
Read-only
Cannot assign.
Immutable
🔄04
Loop bound
0 to n−1.
Pattern
⚠05
Emoji
UTF-16 units.
Pitfall
❓ Frequently Asked Questions
String.length returns a non-negative integer counting UTF-16 code units in the string. For most English text each letter, digit, or symbol counts as 1. Empty strings return 0.
Yes. Every character in the string counts—letters, digits, spaces, tabs, newlines, and punctuation all add to length.
No. length is read-only and strings are immutable. To shorten text, create a new string with slice, substring, or similar methods.
Some emoji and rare characters use two UTF-16 code units (a surrogate pair). length counts code units, not visible graphemes. Use [...str].length, Intl.Segmenter, or a library for user-visible character counts.
Yes. Primitives auto-box when you read .length, and String objects expose the same property. Both return the same number for the same text.
String.length has been part of JavaScript since ES1. It works in every browser and Node.js version without a polyfill.
Did you know?
Arrays and strings both expose .length, but they behave differently. Array length can be assigned to truncate or extend an array; string length is always read-only because strings themselves never mutate.