Strings are made of a sequence of characters. JavaScript allows us to count those characters.
Try running this code in the editor:
"my string".length
The result is 8
. Each character, including the space, is counted.
length
is a property that all strings have. Properties are values that belong to an object. We will work with objects and properties more later. For now, it is important to know that:
- we use the dot operator (
.
) to access properties of an object - strings are objects
- all strings have a
length
property that returns the number of characters in the string
Counting Escaped Characters
Try running this in the console:
"a \"healthy\" dessert".length
The result is 19
. Both of the backslashes are ignored, as they escape the double quotation marks directly after them. The \"
combo is treated as a single character.
Any escaped character will only be counted once, even though we have to type the backslash as an additional character.
In a Function
When we pass a string into a function as an argument, we access it by name of the argument. Run this function in the editor:
function countStringLength(theString) {
return theString.length;
}
countStringLength("example text");