JavaScript String Length

JavaScript String Length | In this quick article, we’ll learn how to get length of string in JavaScript. We’ll additionally explore how JavaScript calculates the length of a string.

In JavaScript, the string length property is often used to obtain the length of a string. Despite the fact that this property is frequently used in conjunction with other JavaScript methods, it is vital to note that length is not a function in itself. The length of a string instance is a read-only data property. The length of an empty string is 0.

The property’s name is static. The logic of the String function (imprecisely, the number of actual parameters it has), which is 1, is independent of the length of strings.

What method does JavaScript use to determine the length of a string?

The length of the string is not returned by JavaScript; instead, the code units consumed by the string are returned. It stores characters using UTF-16 string formatting methods. This simply implies that before being stored, the characters in the string are converted into a 16-bit long binary number.

JavaScript searches up and returns the number of code units contained by the string whenever the. The length property is used. This is why when some characters, such as emojis, use the length property, JavaScript returns 2. This is due to the fact that these symbols take up two code units.

How to Get Length of a String JavaScript

The length function in JavaScript can be used to determine the length of a string. Because the length is a property, it must be accessed through a string class object.

Here is the syntax for using the length property:- string.length
The string whose length we want to return is referred to as “string.”

Let us see an example of JavaScript length of string,

let str = 'This is Know Program. Welcome, everybody!';
console.log(str.length);

Output:-

41

The string is 41 characters long. We used to have ways where the length attribute would return a greater number if only a few characters were present. Below is an instance of the same.

We’ve used the length attribute on a string with an emoji in this example:

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

Output:-

2

The console will return zero if the string is empty. Example to fin length of empty string.

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

Output:-

0

This brings us to the end of this article and we saw how to use the string.length() function in your JavaScript code. 

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *