Spot the Bug #3 - What is this?

📆 · ⏳ 2 min read ·

Welcome to the third edition of “Spot the Bug”

This Week’s Challenge

Consider the following JavaScript code snippet:

var person = {
name: "John",
greet: function() {
console.log("Hello, " + this.name + "!");
}
};
var greetFunction = person.greet;
greetFunction();

We have a person object with a name property and a greet method. We then assign the greet method to a variable called greetFunction and call it.

Run the code yourself, do you see the person’s name being logged to the console? If not, why?

Take a moment to think, and when you’re ready, hit reply with your answer!


Previous Week’s Answer — Spot the Bug #2

In the second edition of Spot the Bug ↗️, we presented the following code snippet, were you able to solve it?

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}`);

Let’s understand the bug and its resolution in more detail.

The Bug Explanation

In this code, what we wanted was to find the largest number from the array however the bug is that it logs undefined for largestNumber when calling findLargest().

This occurs because the largest variable is declared within the if block, but its scope extends beyond the block due to variable hoisting, leading to an undefined value.

The Resolution

To fix this bug, you can declare the largest variable outside the loop and initialize it to a suitable initial value before the loop, like this:

function findLargest(numbers) {
var largest = -Infinity;
for (var i = 0; i < numbers.length; i++) {
if (numbers[i] > largest) {
largest = numbers[i];
}
}
return largest;
}

This was again related to how lexical scoping works in JavaScript, and how closures capture variables, not their values, at the time of creation.

Once again, read more about Closures and Lexical scoping in JavaScript ↗️ to understand it in more detail.

See you in the next edition of “Spot the Bug”!

Akash Rajpurohit.

Credits

Need help with your software project? Let’s talk