Welcome to the second edition of “Spot the Bug”
We wanted to create a function called
findLargest which finds the largest number in an array of numbers, but for some reason it is actually not working as expected.
Your task is to spot the bug in this code. It might seem deceptively simple at first glance, but there’s a sneaky issue hidden in there.
Take a moment to think, and when you’re ready, hit reply with your answer!
In the first edition of Spot the Bug ↗️, we presented the following code snippet, were you able to solve it?
Let’s understand the bug and its resolution in more detail.
setTimeout callback, the variable
i was shared among all the timeouts, and when they executed, they all saw the final value of
i, which was 6.
There are multiple ways to fix this, let’s see some examples:
One way is that you can use an IIFE (Immediately Invoked Function Expression) to capture the value of
i at each iteration. Here’s the corrected code:
Another one is to use a blocked scoped variable using
let instead of
var. Here’s the corrected code:
I hope this explanation helps clarify the bug and its resolution. Keep those debugging skills sharp, and stay tuned for more challenges!
- Icons from Freepik ↗️