Problem Statement
What is the difference between charAt() and bracket notation for accessing characters?
Explanation
CharAt and bracket notation both access characters at a specific index, but handle invalid indices differently.
CharAt returns an empty string for out-of-bounds indices.
Bracket notation returns undefined for out-of-bounds indices.
Both return the same result for valid indices.
Bracket notation is more modern and commonly used.
CharAt exists for backwards compatibility with older JavaScript.
Code Solution
SolutionRead Only
const str = 'Hello';
// Both work for valid indices
console.log(str.charAt(0)); // 'H'
console.log(str[0]); // 'H'
console.log(str.charAt(4)); // 'o'
console.log(str[4]); // 'o'
// Different for invalid indices
console.log(str.charAt(10)); // '' (empty string)
console.log(str[10]); // undefined
console.log(str.charAt(-1)); // '' (empty string)
console.log(str[-1]); // undefined
// Common use cases
// Get first character
const first = str[0];
// Get last character
const last = str[str.length - 1];
// Check if character exists
if (str[5] !== undefined) {
console.log('Character exists');
}
// charCodeAt() - returns Unicode value
console.log(str.charCodeAt(0)); // 72 (Unicode for 'H')
// Loop through characters
for (let i = 0; i < str.length; i++) {
console.log(str[i]); // H, e, l, l, o
}
// Modern way - for...of
for (const char of str) {
console.log(char); // H, e, l, l, o
}Practice Sets
This question appears in the following practice sets:
