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
Example
#const course = 'JavaScript'
const empty = ''
console.log(course.length)
console.log(empty.length)
console.log(course[course.length - 1])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
#string.lengthMore examples
#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'))const reaction = 'Super👍'
console.log(reaction.length)
console.log([...reaction].length)
console.log('café'.length)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))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
#- String.prototype.slice()Returns a portion of a string from a start index to an end index (not included). Supports negative indexes.
- String.prototype.at()Returns the character at the given index. Negative indexes count from the end, so at(-1) is the last character.
- String.prototype.trim()Removes whitespace from both ends of a string: spaces, tabs, and newline characters.
- String.prototype.padStart()Pads a string on the left with the given text until it reaches the specified length. Perfect for leading zeros.
- Array.prototype.lengthThe number of elements in the array, which you can also change.
Spotted a mistake or missing an example? Write to us.