Spot the Bug #2 - Largest number

📆 · ⏳ 2 min read ·

Welcome to the second edition of “Spot the Bug”

This Week’s Challenge

Consider the following JavaScript code snippet:

function findLargest(numbers) {
for (var i = 0; i < numbers.length; i++) {
if (numbers[i] > largest) {
var largest = numbers[i];
}
}
return largest;
}
const numbers = [10, 5, 20, 15];
const largestNumber = findLargest(numbers);
console.log(`The largest number is: ${largestNumber}`);

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?

function countToFive() {
for (var i = 1; i <= 5; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}
}
countToFive();

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:

function countToFive() {
for (var i = 1; i <= 5; i++) {
(function(j) {
setTimeout(function() {
console.log(j);
}, 1000);
})(i);
}
}
countToFive();

Another one is to use a blocked scoped variable using let instead of var. Here’s the corrected code:

function countToFive() {
for (let i = 1; i <= 5; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}
}
countToFive();

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

Need help with your software project? Let’s talk