Essential JavaScript
Introduction
JavaScript Basics
Numbers
Strings
Logic
Variables
Loops
Objects
Arrays
Going Further
Essential JavaScript
Introduction
JavaScript Basics
Numbers
Strings
Logic
Variables
Loops
Objects
Arrays
Going Further
String Length
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");
Learning Goals
I can find the number of characters in a string
I know how to access a property of an object
I know how JavaScript counts escaped characters when determining the length of a string
Code Editor
Click "Run Code" to execute your JavaScript in a secure sandbox and see the output below.
Console Output
0 output lines