String Properties
Overview
In JavaScript, primitive values like strings cannot theoretically have properties or methods because they are not objects.
However, JavaScript uses a feature called 'Auto-Boxing'. When you try to access a property on a string, JS temporarily wraps the primitive string in a String object, accesses the property, and then discards the object.
The most commonly used property is .length, which returns the total number of characters in the string (including spaces and punctuation).
Syntax
const text = "Hello World";
console.log(text.length); // 11 (Space is counted!)
// Example of an empty string
const empty = "";
console.log(empty.length); // 0const str = "JavaScript";
// Strings are zero-indexed, just like Arrays!
console.log(str[0]); // "J" (First character)
console.log(str[4]); // "S"
// Grabbing the LAST character dynamically
console.log(str[str.length - 1]); // "t"Common Pitfalls
- Treating
.lengthas a function. A very common beginner mistake is writingtext.length(). Because length is a property and not a method, this throws aTypeError: text.length is not a function.
Interview Questions
JavaScript automatically coerces primitive strings into String objects under the hood for a fraction of a second when a method or property is called on them. This is known as 'Auto-boxing'.
Real-World Example
Validating that a user's chosen password meets the minimum security requirements.
const password = passwordInput.value;
if (password.length < 8) {
showError("Password must be at least 8 characters long.");
}Check Your Knowledge
Test your understanding of String Properties with these quick questions.