The string length property fetches all the characters included within a string.
Syntax
The syntax for the string length is as follows:
This property simply gives back the total characters available in the string at run time.
Let us try out a couple of examples that use the string length property.
Examples
First, you will see the basic implementation of this property. Later, you will see its application.
Suppose you have the following string:
If you want to know the number of characters in this string, simply apply the string length property as follows:
As you can see, this simply returns the length of the specified string.
You can use this property in multiple places. For example, say you are doing a check-in on an “IF” statement, like the one below:
console.log("It's a short string");
} else {
console.log("It's a long string");
}
And, as you can see in the console output, the statement “It’s a short string” is printed. That is great.
You can use this in the conditional statement of the for loop, as well. If you want to iterate from each of the characters in a string and convert every letter into a lower-case letter, but you are not yet aware of how many characters the string has, then you can simply give the str.length property as a conditional statement.
console.log(str[i].toUpperCase());
}
As you can see in the output console, every character is shown in the console separately and converted into uppercase letters, as well.
So, this is how you can apply it to a lot of different scenarios according to your needs.
Interesting Fact
Here is an interesting fact for you guys. Let us now try to dodge the string length property by assigning it a numeric value. You will see that it will either print the assigned value or the real length of the string.
So, first, assign it a value
And now, we will try to console the length of the string.
And, as you can see, it does not show the assigned value. It shows that the length of the string or the number of characters in the string are being calculated at run time, and then it displays the output.
Conclusion
In this article, you learned what the string length property is in Javascript and you have seen its applications in a few different examples. I hope this article proved helpful in understanding the string length property and its implementations. You can read on to learn more about Javascript at linuxhint.com.
from Linux Hint https://ift.tt/356uzM5
0 Comments