DEV Community

Cover image for Coding Challenge: Can You Spot the Bug? 🔎🐛

Coding Challenge: Can You Spot the Bug? 🔎🐛

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 😎

Coding Challenge

Want more practice challenges and interview prep resources?
👉 https://www.beyondcode.app

Top comments (4)

Collapse
 
anton1ja profile image
a

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]

Collapse
 
beyond_code_app profile image
David Thurman @ BeyondCode.app Beyond Code

Yes! The loop currently will result in an out of bounds exception and crash. We actually need to address this in 2 places:

  1. The initial for loop should be for (let i = 0; i < word.length - 1; i++) Note the length - 1
  2. And like you mentioned, we need to address the comparison line. So it would be if (word[i] !== word[word.length - 1 - i])

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 :)

Collapse
 
anton1ja profile image
a

Thank you for the feedback!

Collapse
 
beyond_code_app profile image
David Thurman @ BeyondCode.app Beyond Code

Anyone think they know the answer? 🤔