# How to write cleaner code, and learn new methods?

Hello, I’m in the algoritm scripting section, and completing the challenges at a good pace. As I have completed the exercises and checked the solutions, they look so easier and cleaner than mine. They use these fancy methods that I have never touched such as map and reduce.

It makes me also a bit discouraged, because usually i complete the challenges with loops , if and else if statements. How will i learn to use the more advanced methods and write cleaner code?

My code:

``````function largestOfFour(arr) {

let num;
let newArr = [];

for (let i = 0; i < arr.length; i++){
for (let b = 0; b < arr[i].length; b++){

if (b === 0){

num = arr[i][b]

} else if (b !== arr[i].length - 1 && arr[i][b] > num){

num = arr[i][b];

} else if (b === arr[i].length - 1 && num <= arr[i][b]){

num = arr[i][b];
newArr.push(num)
num = undefined;

} else if (b === arr[i].length - 1 && num > arr[i][b]){

newArr.push(num);

}
}
}
return newArr;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);`
``````

The “better and cleaner solution” :

``````function largestOfFour(arr) {
return arr.map(function(group) {
return group.reduce(function(prev, current) {
return current > prev ? current : prev;
});
});
}
``````

Just because code is shorter and uses more high order functions does not make it better.

I would focus on making correct and readable code. (For example, your code is correct, but the large number of extra lines make it a bit hard to read)

Once you have correct and readable code, you will begin to see ways to make your code more efficient or better structured as you continue to practice coding.

Learning high order functions is a separate topic which is covered later in the freeCodeCamp curriculum. Those functions offer more compact ways to express the same logic found in code that only uses C style loops, so it is important to have a good grasp on the fundamental logic with the loops before trying to express that logic in high order functions.

And, bust because a solution can/does use a high order function does not mean it is the best choice. There are a few solutions that use high order methods just to demonstrate their use but are actually more efficient when rewritten with simpler logic and C style loops.

Do you have any suggestions on how to get better at writing cleaner code?

‘Clean code’ is a gimicky term. I’d focus on correct and readable code.

Correct - it always produces the intended result

Readable - someone else could look at your code and easily understand what it is doing and how

For readability, I’d focus on good variable names, consistent formatting that matches conventions, good organization, and occasional comments to explain your logic.

It can be very helpful to edit your code once you have it correct to improve its readability. Reviewing your code and editing it is a critical skill and it greatly improves the quality of code.

1 Like