length and character access
Learn the length property and accessing characters with brackets.
String length: length
Every string has a property called length that returns the number of characters in the string. For example "hello".length is 5.
An empty string "" has a length of 0. Digits, spaces and punctuation all count as one character each; JavaScript counts characters with UTF-16.
You access the property with a dot: const word = "pen"; console.log(word.length);. This prints three.
Character access: brackets
You reach a single character in a string with brackets like word[0]. Indexing starts at zero: the first character is 0, the second is 1, the last is length - 1.
For example "pen"[0] gives "p", "pen"[2] gives "n". An out of range index returns undefined; no error is thrown.
The same access works with the charAt(0) method; its only difference is that an out of range index returns an empty string.
Exercise Log length and characters
Declare word as the string "JavaScript". Log word.length, the first character word[0], and the last character word[word.length - 1] with console.log.
Show example solution
const word = "JavaScript";
console.log(word.length);
console.log(word[0]);
console.log(word[word.length - 1]);
Test yourself
-
What is "hello".length?
console.log("merhaba".length);- 3
- 4
- 5
- 6
Show answer
5 — Correct. 'hello' has five letters; length returns 5.
-
Access the first character
const word = "kalem"; const first = word____;Show answer
const word = "kalem"; const first = word[0]; -
Match each access to its meaning
- word[0]
- First character
- word.length
- Character count
- word[word.length - 1]
- Last character
- word.charAt(0)
- First character (method)
-
What is "pen".length - 1?
console.log("kalem".length - 1);- 3
- 4
- 1
- 2
Show answer
2 — Correct. 'pen' has length 3; 3 - 1 = 2. This is the last character's index.