JavaScriptStrings

String.prototype.length

The length of a string, i.e. the number of UTF-16 code units. The property is read-only.

Returns
A non-negative integer: the number of UTF-16 code units in the string.
Changes the original
No
On this page

Example

#
JavaScript
const course = 'JavaScript'
const empty = ''

console.log(course.length)
console.log(empty.length)
console.log(course[course.length - 1])
Console
10
0
t

Definition and usage

#

The length property tells you how many characters make up a string. An empty string "" has a length of 0, and the last character is always at index length - 1. It's not a method, so you write it without parentheses.

More precisely, length counts UTF-16 code units. Ordinary letters take up one unit each, but many emoji and rarer symbols take up two, which is why "👍".length is 2. To count the number of visible characters, [...text].length works better, though for emoji made of several parts (like one with a skin tone modifier) even that is not enough, and you will want Intl.Segmenter.

Strings are immutable, so length is read-only. You can't shorten a string by assigning it a smaller number, and in strict mode you will even get an error. To cut a string short, create a new one with slice().

Syntax

#
Syntax
string.length

More examples

#
Validating a nickname length
JavaScript
function validateNickname(nickname) {
  const trimmed = nickname.trim()
  if (trimmed.length < 3) return 'Nickname too short'
  if (trimmed.length > 16) return 'Nickname too long'
  return 'OK'
}

console.log(validateNickname('Al'))
console.log(validateNickname('  CodeWarrior  '))
console.log(validateNickname('SuperProgrammer2026'))
Console
Nickname too short
OK
Nickname too long
Emoji counted twice
JavaScript
const reaction = 'Super👍'

console.log(reaction.length)
console.log([...reaction].length)
console.log('café'.length)
Console
7
6
4
Truncating long text
JavaScript
function truncate(text, max) {
  return text.length > max ? text.slice(0, max - 3) + '...' : text
}

console.log(truncate('Introduction to programming', 15))
console.log(truncate('HTML', 15))
Console
Introduction...
HTML

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • When enforcing a character limit, for example in a description field, remember that emoji can count as two units. If the limit is about what the user actually sees, count with [...text].length.
  • When checking whether a field is empty, strip spaces first: text.trim().length === 0.

Related entries

#

Spotted a mistake or missing an example? Write to us.