DEV Community

Discussion on: Why do we write JavaScript like this?

Collapse
 
sargalias profile image
Spyros Argalias • Edited

It's about readability and understandability.

I never aim to write functional code. I aim to write what I consider to be the best code I can write.

First example

In the palindrome example, the function body is 2 lines long:

function isPalindrome(str) {
    const reversedStr = str.split('').reverse().join('');
    return reversedStr === str;
}

The function body of the loop version has 4 lines of code and a few more lines with braces. The volume of code to read is much higher, and you must read all of it before you understand what it's doing. Furthermore, you have to actually parse the logic in your head and see how it works, which I find much more difficult than the simpler logic in the functional example.

"reverse the string and check if it's equal to the original", compared to "loop through the string, for each index, grab the current character, check if the current character is equal to the character at the index from the opposite end of the string and return false if it isn't".

It just takes longer to read and understand for someone who is well-versed in both versions.

About performance: In many apps, it brings no benefit to optimise performance for simple things (premature optimisation). It's usually better to optimise for readability and only optimise for performance if needed.

Second example

I would have written the second example like this:

import {add} from 'ramda';

const sum = (...args) => args.reduce(add, 0);

Using a library, or coding your own versions of these utilities, is fine, since you'll reuse those functions in many places throughout your codebase (DRY).

Again, if you understand what this is doing (which just takes a bit of practice), this is instant to read and understand. It says, "for every item in the list, add it to the total, with the total starting at 0".

The for-loop version is fine, but again, you have to read every word and parse it to understand it.

And so on.

Edit: Fixed the code.