Common Pitfalls with indexOf() and -1
You'll learn how to avoid a frequent bug when checking if indexOf() found a substring.
The Core Problem
You already know that indexOf() returns the position of a substring, or -1 if it's not found. The pitfall? Using indexOf() directly in a condition without properly checking for -1.
Here's why this matters: In JavaScript, any number except 0 is truthy—including -1. So if you write if (str.indexOf("hello")), it evaluates to true when the substring is NOT found (because -1 is truthy), and false only when found at position 0.
The Wrong Way
let message = "Welcome to JavaScript";
// WRONG: This checks truthiness of the return value
if (message.indexOf("Welcome")) {
console.log("Found it!"); // This won't run! (indexOf returns 0)
}
Since "Welcome" starts at position 0, and 0 is falsy, this condition fails even though the substring exists.
The Right Way
Always explicitly compare the result to -1:
let message = "Welcome to JavaScript";
// CORRECT: Check if NOT equal to -1
if (message.indexOf("Welcome") !== -1) {
console.log("Found it!"); // This runs correctly
}
// Or check if greater than -1
if (message.indexOf("JavaScript") > -1) {
console.log("Also found!");
}
Think of it like searching a library shelf: The librarian tells you "It's on shelf 0" or "Not found (-1)". You wouldn't ask "Did you find a shelf?"—you'd ask "Did you find a valid shelf number?"
Key Takeaway: Always check indexOf() !== -1 or indexOf() > -1 to determine if a substring exists. Never rely on the return value's truthiness alone.