Try   HackMD

:::section{.main}

The string length property in JavaScript returns the length of string in UTF-16 code units. It returns 0 when the string is empty, , it's length. JavaScript uses a UTF-16 string format to depict the most common characters, consisting of a 16-bit data unit. The value returned by length does not match the number of characters in the string. When a string is empty, its length is 0.

:::

:::section{.main}

Syntax

The syntax of string length property in JavaScript is:

string.length

Where string is the name of the string.
The string length property in JavaScript doesn't take any parameters.
:::

:::section{.main}

Return Value

The string length property will return the number of characters present in the string.
:::

:::section{.main}

Examples

JavaScript Code to Show the Working of string.length Property

//JavaScript code to show the working of the `string.length` property
let name = 'Hello';
let empty = '';

console.log('The length of ' + name + ' is ' + name.length + ' code units long');

console.log('The length of the empty string is ' + empty.length);

Output:

The length of Hello is 5 code units long
The length of the empty string is 0

Assigning to length

let name = 'Hello';
let len = name.length;

console.log('The length of string '+ len);

Output:

The length of string 5

:::

:::section{.main}

Browser compatibility

Browser length
Chrome 1
Edge 12
Firefox 1
Internet Explorer 3
Opera 3
Safari 1
WebView Android 1
Chrome Android 18
Firefox for Android 4
Opera Android 10.1
Safari on iOS 1
Samsung Internet 1.0
Deno 1.0
Node.js 0.10.0

:::
:::section{.summary}

Conclusion

  • The string length property in JavaScript determines the length of the string, that is, the number of characters it contains.
  • Internally, to calculate the number of characters, it counts the number of code units occupied by the string.
  • In the case of an empty string, it returns 0.

:::