Welcome to the second edition of “Spot the Bug”
This Week’s Challenge
Consider the following JavaScript code snippet:
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!
Previous Week’s Answer — Spot the Bug #1
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.
The Bug Explanation
The bug in this code was due to a closure issue. JavaScript closures capture variables, not their values, at the time of creation.
In the 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.
The Resolution
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:
Read more about Closures and Lexical scoping in JavaScript ↗️ to understand this bug in more detail.
I hope this explanation helps clarify the bug and its resolution. Keep those debugging skills sharp, and stay tuned for more challenges!
Akash Rajpurohit.
Credits
- Icons from Freepik ↗️