DEV Community

Discussion on: Why do we write JavaScript like this?

Collapse
 
dfockler profile image
Dan Fockler

I think it comes down to the idea that the less state and logic you have to manage the less bugs you'll end up with. Now that might not be true, but intuitively it makes sense. If there's less things I have to manage in my head, the easier things are to understand and the harder they are to mess up.

In your capitalizeAllWords example the longer example has 5 variables to manage, while the functional version has 1 variables (the input string). A lot of the code in the imperative version doesn't pertain to what the function is doing (setting up the loop, setting up the intermediate variables, changing the variable state), while the functional version is almost completely just the operations you are interested in to complete the operation, and includes only one logical branch doing the input type check.

I'd argue that speed of execution doesn't really matter at the small scale, for Javascript. For things like rendering a Virtual DOM, it will dwarf the execution time compared to running a small user created function.

Collapse
 
anders profile image
Anders • Edited

Good points for sure. I'd argue the short version has two variables (sentence and word), but I take your meaning : ).

There is ofc more actual "variables" or pieces of data at least than that, just that they are never named, thus potentially they do not count.

The performance reflection is ofc also true, its more the general pattern of not caring that eventually gets us into trouble.