Code debugging tips on the example for loops in JavaScript

Now I will teach you a technique for finding errors in the code. Let's imagine that, due to some misunderstanding, you did not follow the advice from the previous lesson and have got a non-working code. Let's see how to find the errors and make it work.

Many beginners use the wrong search technique. They look at the code, in the hope that they will notice an error. And so for a couple of hours. It doesn't work like that.

The correct technique is to output variables to the console and determine whether there is what you need or not. In this case, you need to start from the alleged place of the problem and move up the code. Let's see in practice.

Let, for example, you were faced with the task of iterating over an array with two-digit numbers and finding numbers whose first digit is one greater than the second. Let the array store numbers as strings for simplicity.

Let you solve the problem and get the following code:

let arr = ['21', '32', '34', '43', '45', '54', '55']; let sum = 0; for (let elem of arr) { if (elem[0] === elem[1] + 1) { sum += elem; } } console.log(sum); // shows 0

The code, however, outputs 0. In this case, the first thing to check is to see what is in the variable, whether the code execution falls into the if. Output something in it to the console:

let arr = ['21', '32', '34', '43', '45', '54', '55']; let sum = 0; for (let elem of arr) { if (elem[0] === elem[1] + 1) { console.log('!'); // outputs nothing sum += elem; } } console.log(sum);

Since nothing appeared in the console, this means that the code execution simply does not enter the condition. Let's see with our own eyes what we compare:

let arr = ['21', '32', '34', '43', '45', '54', '55']; let sum = 0; for (let elem of arr) { console.log(elem[0], elem[1] + 1); // '2' and '11', '3' and '21' ... if (elem[0] === elem[1] + 1) { sum += elem; } } console.log(sum);

As a result, it immediately becomes clear that the second term is two-digit. It is easy to understand that this is because the unit is added as a string. Let's fix the problem:

let arr = ['21', '32', '34', '43', '45', '54', '55']; let sum = 0; for (let elem of arr) { if (+elem[0] === +elem[1] + 1) { // correction sum += elem; } } console.log(sum); // '021324354'

After the correction, we can already see that something has appeared in the variable sum, although it is incorrect. It can be seen, however, that what we need is there, but it is concatenated like strings, and not numbers. Let's fix the problem:

let arr = ['21', '32', '34', '43', '45', '54', '55']; let sum = 0; for (let elem of arr) { if (+elem[0] === +elem[1] + 1) { sum += +elem; // correction } } console.log(sum); // everything is working

Fix the errors in the following code:

let obj = {a: 10, b: 20, c: 30, d: 40, e: 50}; let sum = 0; for (let elem in obj) { if (elem[0] === '1' && elem[0] === '2') { sum += +elem; } } console.log(sum);
enru