Description
The JavaScript String property length
returns the number of characters (or length) in a string.
Syntax
The property length
has the below syntax, where str
is a string.
str.length
Parameters
The property length
doesn't take any properties.
Result
The property length
returns the number of characters in a string.
Example 1: Using the Property
The property simply returns the size of a string.
var str = "Hello World!";
// Finding length of a string
document.write(str.length); // Prints: 12
// Finding length of a blank string
document.write("".length); // Prints: 0
// Finding length of a null value
document.write(null.length); // Returns error
Output:
12
0
Example 2: Finding Length of a Null
The fromIndex
is used to find the position from where the backward search must perform within the string.
// Finding length of a null value
document.write(null.length); // Returns error
Output:
Uncaught TypeError: Cannot read properties of null (reading 'length')
Example 3: Length Property is Read-Only
The property length
is a read-only property and we cannot assign a value to overwrite a string length.
var str = "Hello World!";
// Finding length of a string
document.write(str.length); // Prints: 12
str.length = 5;
// Finding length of a string
document.write(str.length); // Prints: 12
Output:
12
12
Example 4: Using Length Property to Read Characters of a String
We can use the property length to read the ending characters of a string.
var str = "Hello World!";
// Reading the last character of a string
document.write(str[str.length - 1]); // Prints: !
// Reading the second last character of a string
document.write(str[str.length - 2]); // Prints: d
Output:
!
d
Overall
The JavaScript String property length
returns the number of characters in a string.