In this guide, we explain how to measure the length of a string in JavaScript using the length method.
JavaScript is a flexible programming language that runs just about everywhere. You can run JavaScript apps in web browsers, build command-line apps you can run in the terminal, mobile apps can be built using platforms like Cordova, and server processes can be written on platforms like Node.js.
Naturally, Linux is the environment of choice for many JavaScript developers and is perfect for learning tools like Node.js as well as hosting them for end users once completed.
JavaScript Strings
JavaScript strings are primitive variables, one of the basic types of variables used for storing text. A string is a sequence of characters only, and should not be used for storing numbers or complex objects, but things like names, addresses, and phone numbers.
Finding Out the Length of a String
var name = "Billy Smith"; console.log(name.length) // Returns 11
Note that:
- Every character is counted – including spaces!
- If the string value is “”, its length will be 0
Conclusion
Reading a string’s length may seem trivial, but it’s very useful. For example, you might need to check that the user has entered only a short name and not a paragraph of text, or want to check whether the user has forgotten to enter their name at all.
To learn more about other JavaScript statements and functions, check out other articles!