JavaScript String length Property

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Instance property

What You’ll Learn

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

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.

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.

JavaScript
const greeting = "Hello, World!";
console.log(greeting.length); // 13

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.

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.

📝 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.

⚡ Quick Reference

GoalCode
Get character countstr.length
Empty checkstr.length === 0
Minimum lengthstr.length >= 8
Last valid indexstr.length - 1
Writable?No (read-only)
Emoji caveatCounts UTF-16 units, not graphemes

📋 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)

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.

JavaScript
const greeting = "Hello, World!";

console.log(greeting.length);        // 13
console.log("".length);              // 0
console.log("  spaces  ".length);    // 10 (spaces count too)
Try It Yourself

How It Works

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
Try It Yourself

How It Works

length gives you a fast size check without regex or loops. Pair it with strength rules (uppercase, digits) separately for full password policies.

Example 3 — Loop Over Every Character

Use length as the loop bound to build a reversed string.

JavaScript
const word = "CodeToFun";
let reversed = "";

for (let i = word.length - 1; i >= 0; i--) {
  reversed += word[i];
}

console.log(reversed); // "nuFoTedoC"
Try It Yourself

How It Works

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
Try It Yourself

How It Works

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.

JavaScript
<textarea id="textInput" rows="4" cols="40"></textarea>
<p id="charCount">Characters: 0</p>

<script>
  const textarea = document.getElementById("textInput");
  const charCount = document.getElementById("charCount");

  textarea.addEventListener("input", () => {
    const length = textarea.value.length;
    charCount.textContent = "Characters: " + length;
  });
</script>
Try It Yourself

How It Works

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.

🚀 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.

Important Considerations

  • Multibyte characterslength 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 sizelength 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.

📝 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.

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 Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
String.length Excellent

Bottom line: Safe everywhere for basic counting. Use Intl.Segmenter when emoji-accurate user limits matter and you can target modern browsers.

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.

💡 Best Practices

✅ Do

  • Use length for quick size and empty checks
  • Validate min/max before saving user input
  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about String.length

Your foundation for counting and validating text in JavaScript.

5
Core concepts
🔢 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.

Continue to String prototype

Learn where shared methods like toUpperCase and slice live on the prototype chain.

prototype tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful