At Beyond Code, we’re all about helping new devs get job-ready and ace their interviews.
So here’s a quick one for you: Can you spot the bug?
Drop your answer in the comments. First correct one gets bragging rights 😎
Want more practice challenges and interview prep resources?
👉 https://www.beyondcode.app
Top comments (4)
The loop would return false in the first iteration already. For example for the word 'level', word length is 5. In the 1st iteration i = 0, so:
word[i] = word[0] = l
word[word.length - i] = word[5 - 0] which is out of range because indexes here go from 0 to 4
One way to fix this would be to put word[word.length - 1 - i]
Yes! The loop currently will result in an out of bounds exception and crash. We actually need to address this in 2 places:
Bonus: If you really want to get fancy, you can also change the initial for loop to be for(let i = 0; i < word.length / 2; i ++) since you technically only need to iterate half the array (while checking the back half) to confirm its a palindrome :)
Thank you for the feedback!
Anyone think they know the answer? 🤔