When accessing string characters with indices, the most common problem we can run into is exceeding the string's bounds.
Remember, the characters of a string are normally indexed from 0 to length - 1.
Any index which is strictly greater than length - 1 is invalid.
When you try to access a character with an invalid index, JavaScript returns undefined:
let car = "ford";
// Valid indices: 0, 1, 2, 3
console.log(car[0]); // Output: f
console.log(car[3]); // Output: d
// Invalid indices: 4, 30
console.log(car[4]); // Output: undefined
console.log(car[30]); // Output: undefined
Some languages like Python wouldn't even let this code run, but throw an IndexError. JavaScript is more permissive, which is not necessary a good thing.
As a programmer, I'd rather be told when I made a mistake early on so I can fix it, instead of running into problems later on and not knowing what the root of those problems is.
In conclusion, we always want to double check our code to make sure that we don't exceed one string's bounds in our programs.
Assignment
Follow the Coding Tutorial and let's practice with string bounds!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
