Suppose you’ve stored the following string in a variable called
let myString = "The quick brown fox jumps over the lazy dog.";
Now let’s suppose that, for one reason or another, you need to calculate the length of this string. What’s the best way to do that?
As explained in the MDN Web Docs,
length is a read-only property that contains the length of the string in UTF-16 code units.
To reference it, use the following syntax:
And don’t forget to replace
String with the name of your constant or variable!
Building on our example above, here’s how we would reference the length property of the
let myString = "The quick brown fox jumps over the lazy dog."; console.log("This string is " + myString.length + " characters long.");
For an empty string, the length property is 0.
Up next: You should know that the length property counts everything in your string. If your string contains special characters, such as new lines/line breaks, they are included in the count. See our tutorial to learn how to remove them.