How to get the Length of a String in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 15 20211 min read

banner

Photo by Sergey Fediv

Get a String's Length in JavaScript #

Use the length property to get a string's length. For example, 'abc'.length returns 3. The length property is read only and returns the string's length. If accessed on an empty string, the property returns 0.

index.js
const str = 'abc'; console.log(str.length); // ๐Ÿ‘‰๏ธ 3 console.log(''.length); // ๐Ÿ‘‰๏ธ 0 console.log(' '.length); // ๐Ÿ‘‰๏ธ 2 console.log('test-'.length); // ๐Ÿ‘‰๏ธ 5

In all of the examples we use the length property to get the string's length.

Note that empty space or any other character gets counted.

The length property only returns 0, if called on an empty string.

The length property of a string is read only and cannot be set by the user.

index.js
let str = 'abc'; str.length = 10; console.log(str.length); // ๐Ÿ‘‰๏ธ 3

Even after we tried to set a new value to the string's length property it remained unchanged.

This behavior is different from setting the length property on an array.

index.js
const arr = ['a', 'b', 'c']; arr.length = 5; console.log(arr.length); // ๐Ÿ‘‰๏ธ 5
It's important to note that strings are immutable in JavaScript. You can never change the contents of a string, instead you have to create a new string.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee