Javascript · Strings
Indexing
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — What is String Indexing?
Strings are like a sequence of characters lined up in order. Each character has a position called an index. Think of it like numbered boxes, where each box holds one character!
Let's look at the name "Aquachu":
let name = "Aquachu";
// A q u a c h u
// 0 1 2 3 4 5 6
console.log("The string has", name.length, "characters");
console.log("Indices go from 0 to", name.length - 1);
Why Start at 0?
In programming, we count starting from 0, not 1. This is called zero-based indexing. So the first character is at index 0, the second at index 1, and so on. It might feel weird at first, but you'll get used to it!
Exercise 2 — Accessing Characters with []
To access a character at a specific position, we use square brackets
[]
with the index number inside.
let codemon = "Pyrochu";
// Access individual characters
console.log("First character:", codemon[0]); // "P"
console.log("Second character:", codemon[1]); // "y"
console.log("Last character:", codemon[6]); // "u"
If you want to access characters dynamically, you can use expressions inside the brackets.
let codemon = "Pyrochu";
let last_char = codemon[codemon.length - 1];
console.log("Last character (dynamic):", last_char);
Remember: Since indexing starts at 0, the last character is always at index
length - 1
!
Exercise 3 — Find the Character
Given the following code, what will be displayed?
let name = "Florachu";
console.log(name[3]);
Options
• "r"
• "F"
• "o"
• "a"
Hint : Remember that indexing starts at 0. Count the positions: F is at index 0, l is at index 1, o is at index 2...
Exercise 4 — Access the First and Last Character
Complete the code to access the first and last character of the string.
let codemon = "Aquachu";
let firstChar = codemon____;
let lastChar = codemon[codemon.____ ____ ____];
console.log(firstChar,lastChar);
Options: [0] [1] length size - + 1 0
Hint : The first character is always at index 0. For the last character, remember that if a string has a ```length``` of 7, the last index is 6 (length - 1).
Exercise 5 — The .charAt() Method
JavaScript provides another way to access characters: the
.charAt()
method. It works similarly to bracket notation, but with a slightly different syntax.
let codemon = "Aquachu";
// Different syntax, same result
console.log("With []:", codemon[0]);
console.log("With .charAt():", codemon.charAt(0));
// Both do the same thing!
console.log("Third character with []:", codemon[2]);
console.log("Third character with .charAt():", codemon.charAt(2));
Both methods work for accessing characters, but they behave differently when the index is out of bounds. We'll explore that next!
Exercise 6 — What Happens with Invalid Indices?
What happens if you try to access a character at an index that doesn't exist? Let's find out the difference between
[]
and
.charAt()
!
let codemon = "Aquachu"; // length is 7, indices 0-6
// Trying to access index 10 (doesn't exist)
console.log("With [] at index 10:", codemon[10]);
console.log("With .charAt() at index 10:", codemon.charAt(10));
// With negative index
console.log("With [] at index -1:", codemon[-1]);
console.log("With .charAt() at index -1:", codemon.charAt(-1));
So, what's the difference when accessing invalid indices?
When accessing an invalid index:
-
[]
returns
undefined
-
.charAt()
returns an empty string
""
Both are safe to use (they won't crash your program), but
.charAt()
is often preferred because it always returns a string.
Exercise 7 — Predict the Output
What will the following code display?
let name = "Pyrochu";
console.log(name.charAt(20));
Options
• ```undefined```
• An empty string ```""```
• An error message
• ```null```
Hint : Remember: ```.charAt()``` returns an empty string when the index is out of bounds, while ```[]``` returns ```undefined```.
Exercise 8 — Match Index to Character
Given the string
"Florachu"
, match each index to its corresponding character.
Items to match
• Index 0
• Index 3
• Index 7
• Index 10
Definitions
• "F"
• "r"
• "u"
• Out of bounds (invalid)
Exercise 9 — Extract Specific Characters
Complete the code to extract the first letter, the middle letter, and the last letter from a Codémon's name.
let codemon = "Pyrochu";
let first = codemon____;
let middle = codemon.____(3);
let last = codemon[codemon.____ - ____];
console.log(first + middle + last);
Options: [0] [1] charAt charCodeAt length size 1 0
Hint : Use bracket notation ```[]``` for the first and last characters. Use ```.charAt()``` for the middle one. Remember that the last index is always ```length - 1```.
Exercise 10 — Codémon Name Analyzer
Create a Codémon name analyzer! Given a Codémon's name:
1. Display the first character
2. Display the last character
3. Display the middle character (use index 3 for "Florachu")
4. Try to access index 50 with both
[]
and
.charAt()
to see the difference
Use
console.log()
with descriptive messages for each step.
Starter code
let codemonName = "Florachu";
// Write your code here
Back to the course