Your main issue is the return false
placement. Let's first walk through the working code and check what it does:
for (let index = 0; index < letters.length; index++) {
if (letters[index] === letters[index + 1]) {
return true
}
}
return false
The above code checks if a letter is the same as a consecutive letter. If it is equal, true
is returned. If it is not equal we'll move on to the next letter. If all letters are checked and no match has been found then return false
.
const letters = ["a", "b", "b", "c"];
// executes as
"a" === "b" // not equal, next!
"b" === "b" // equal, return true
const letters = ["a", "b", "c"];
// executes as
"a" === "b" // not equal, next!
"b" === "c" // not equal, next!
"c" === undefined // not equal, next!
// all letters have been checked (for-loop is complete), return false
Now let's have a look at your code:
for(let i = 0; i < letters.length; i++){
if (letters[i] === letters[i + 1]){
return true
} else{
return false
}
}
The above code checks if a letter is the same as a consecutive letter. If it is equal, true
is returned. If it is not equal, false
is returned. This means that the function is always going to return in the first iteration. The other letters are never checked.
const letters = ["a", "b", "b", "c"];
// executes as
"a" === "b" // not equal, return false
const letters = ["a", "b", "c"];
// executes as
"a" === "b" // not equal, return false
return
is a statement that marks the end of the function. Nothing (within the same function) will be executed after a return
statement, therefore the second iteration of the for-loop will never be reached and other letters are never checked.