How to get the Length of a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 15, 2021

banner

Photo from Unsplash

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.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.