1. What does indexOf() return if the substring is not found?
IndexOf returns minus 1 when the substring is not found in the string. If found, it returns the index of the first occurrence, which is zero or a positive number. You should check if the result equals minus 1 to determine if substring exists. Never use indexOf in a boolean context without comparing, because zero is falsy but a valid index. Modern alternative is the includes method which returns true or false. LastIndexOf works similarly but searches from the end.
const str = 'Hello World';
// indexOf() - returns index or -1
console.log(str.indexOf('World')); // 6 (found at index 6)
console.log(str.indexOf('o')); // 4 (first 'o')
console.log(str.indexOf('xyz')); // -1 (not found)
// Correct way to check existence
if (str.indexOf('World') !== -1) {
console.log('Found!');
}
// WRONG way (don't do this)
if (str.indexOf('Hello')) { // 0 is falsy!
console.log('This will not run!'); // Won't execute
}
// Modern alternative - includes()
console.log(str.includes('World')); // true
console.log(str.includes('xyz')); // false
if (str.includes('World')) {
console.log('Found!'); // Cleaner
}
// lastIndexOf() - searches from end
const text = 'hello hello';
console.log(text.indexOf('hello')); // 0 (first)
console.log(text.lastIndexOf('hello')); // 6 (last)
// Case sensitive
console.log(str.indexOf('world')); // -1 (lowercase not found)
// Starting position
console.log(str.indexOf('o', 5)); // 7 (search from index 5)