Unlock the Power of Strings in JavaScript
Understanding the Length Property
When working with strings in JavaScript, understanding the length
property is crucial. This fundamental property returns the number of characters in a string, allowing you to manipulate and analyze text data with ease.
The Syntax of Length Property
The length
property is simple to use, with a syntax that’s easy to grasp: str.length
. Here, str
is a string, and the property returns the number of characters it contains.
What Does Length Return?
The length
property returns the number of code units in the UTF-16 string format. This means that for most strings, it will return the actual number of characters. However, some rare characters require two code units to be represented, so the length
property might not always return the exact number of characters.
Example 1: Getting the Length of a String
let string1 = 'JavaScript';
console.log(string1.length); // Output: 10
As expected, the output is 10, which is the number of characters in the string ‘JavaScript’.
The Read-Only Nature of Length Property
It’s essential to note that the String.length
property is read-only. Attempting to change it manually will have no effect. For instance:
let string2 = 'Programming';
string2.length = 5; // Trying to change the length property
console.log(string2.length); // Output: 11 (still returns the original length)
As you can see, assigning a new value to string2.length
doesn’t change the original string. The length
property remains unchanged, returning the correct number of characters in the string ‘Programming’, which is 11.
Related Topics
If you’re interested in learning more about JavaScript properties, be sure to check out our articles on:
These resources will provide you with a deeper understanding of how to work with different data types in JavaScript.