As you learn a language, the complexity of your programs grows. It's time to talk about how to write code correctly so that it does what you intended. I will give you a good techniques.
Suppose you are faced with a task of sufficient complexity, for the implementation of which you need to write a certain number of code lines.
The wrong approach would be to try to write the whole solution code and then start testing it. In this case, there is a high probability that nothing will work for you, and you will have to look for the error in a large amount of code.
The correct approach is to break the task into small elementary steps that you will implement and immediately check their correctness. In this case, even if you make a mistake somewhere, you will immediately notice the problem and fix it.
Let's try it in practice. Let for example you have an array with numbers:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
Let your task be to take from this array
those elements that are divisible by
3
and find their sum.
The first small step I would suggest is to simply iterate over the elements of the array and print them to the console. Let's do this and make sure everything works:
for (let elem of arr) {
console.log(elem);
}
Let's now separate those elements that are
divisible by 3
. Let's print them
to the console and make sure we get the
right elements:
for (let elem of arr) {
if (elem % 3 === 0) {
console.log(elem); // shows 3, 6, 9
}
}
Now in the next step we can find the sum of the required elements:
let sum = 0;
for (let elem of arr) {
if (elem % 3 === 0) {
sum += elem;
}
}
console.log(sum);
Given an array:
let arr = [10, 20, 30, 40, 21, 32, 51];
Take from this array those elements
whose first digit is 1
or
2
and find their sum.