String.prototype.length
The length of a string — how many characters it has.
Available since: ES1
Syntax
str.lengthReturn value
numberThe number of characters (strictly, UTF-16 code units) in the string.
Examples
The length of a word:
console.log('Hello'.length);Output:
5Checking that a field is not empty and not too long:
const name = 'Anna';
console.log(name.length > 0 && name.length <= 20);
console.log(''.length);Output:
true
0Notes
It is a property, not a method: no parentheses — str.length, not str.length().
Emoji and some rare characters take two code units, so '😀'.length is 2. To count real characters use [...str].length.
See also
- String.prototype.slice — Returns part of a string.
- Array.prototype.length — The number of elements in an array.
- String.prototype.at — Returns the character at a position; negative indexes are allowed.
Related recipes
In the tutorial
- Strings — Strings in JavaScript — quotes, joining, template literals, length, accessing characters and the first methods.