JavaScript String length
Syntax & Examples


String.length property

The `length` property of String object in JavaScript returns the length of the string. It is read-only.


Syntax of String.length

The syntax of String.length property is:

length

This length property of String reflects the length of the string. Read-only.

Return Type

String.length returns value of type int.



✐ Examples

1 Length of a string with spaces

In this example,

We declare a string variable str with the value 'Hello World'. The length property is then used to get the length of the string which includes spaces.

JavaScript Program

let str = 'Hello World';
console.log(str.length);

Output

11

2 Length of a string with numbers

In this example,

We declare a string variable str with the value '12345'. The length property is then used to get the length of the string.

JavaScript Program

let str = '12345';
console.log(str.length);

Output

5

3 Length of an empty string

In this example,

We declare an empty string str. The length property is then used to get the length of the string, which is 0.

JavaScript Program

let str = ''; // Empty string
console.log(str.length);

Output

0

Summary

In this JavaScript tutorial, we learned about length property of String: the syntax and few working examples with output and detailed explanation for each example.