Fri Oct 15 2021·1 min read
Photo by Sergey Fediv
length property to get a string's length. For example,
length property is read only and returns the
string's length. If accessed on an empty string, the property returns
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.
length property only returns
0, if called on an empty string.
length property of a string is read only and cannot be set by the user.
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.
const arr = ['a', 'b', 'c']; arr.length = 5; console.log(arr.length); // 👉️ 5
I'll send you 1 email a week with links to all of the articles I've written that week