DEV Community

Cover image for Writing modern JavaScript code

Writing modern JavaScript code

Sebastien Castiel on May 20, 2017

Remember when JavaScript was a language used to make elements change on the page when the cursor was over them? These days are over, every language...
Collapse
 
gmaiolo profile image
Guillermo Maiolo • Edited

You're confusing functional programming with extreme immutability, which is an anti-pattern by itself, generating an incredible amount of overhead.
You're literally advocating to loop three times instead of one just to force yourself to use map, filter and reduce.

I understand these are examples, but they're extremely bad examples for any apprentice dev so this needs to be clarified.

While the post correctly encourages having immutable data, the idea is to keep that data updated with pure functions. Now, pure functions must avoid shared state, mutable data, and side-effects outside of their bounds but not necessarily inside, this simple concept may be hard to grasp at first, so let me try to show it with the examples you used:

// Instead of:
const res = arr
  .map(elem => ({ name: elem.name, calculatedValue: elem.value * 10 }))
  .filter(elem => elem.calculatedValue > 100)
  .reduce((acc, elem) => ({
    [elem.name]: calculatedValue,
    ...acc
  }), {})

// Prefer:
const res = (() => {
  let obj = {}
  for (let i = 0; i < arr.length; i++) {
    const calculatedValue = arr[i].value * 10
    if (calculatedValue > 100) {
      obj[arr[i].name] = calculatedValue
    }
  }
  return obj
})()

Of course it may or may not be better to use Object.keys().forEach() or even Object.keys().map() and still loop once doing all the needed calculations on the fly as well, but the point is that yes, pure functions and functional programming should be used, but we must always have in mind that both of them can use and abuse of mutable data correctly contained and that's not bad, it's actually one of the beauties of Javascript.

Collapse
 
tiffany profile image
tiff

Can you give a better example without chaining together map, filter, and reduce but still keeping it functional? Why is it an anti-pattern?

Collapse
 
tqwhite profile image
TQ White II • Edited

Prettier lints like crazy. It enforces an absolute coding standard. It's main virtue is that it only has two configuration options, tabs vs spaces and quotes vs apostrophes. Otherwise, everyone who uses it gets standard, well-formatted code. I am a huge fan.

Collapse
 
ekdikeo profile image
Eric B

If you map, then filter, then reduce an array in code that I manage, you're not getting your code in.

Collapse
 
relativityboy profile image
relativityboy

A nice little article but your first code example for functional programming is misleading.

The array declaration used for both // Instead of: and // Prefer: is shown visually to be a part of the // Instead of: block.

This might suggest to the user at a glance "oh, the new way is prettier". But it's a misrepresentation of what's going on.

Sorry to be a neg, but you're going to sell an idea, you gotta sell the truth.

Collapse
 
scastiel profile image
Sebastien Castiel

You're absolutely right, my bad. It's fixed πŸ˜‰

Collapse
 
moloko profile image
Matt Leathes

whilst array.map and array.forEach are unarguably more readable than for loops, aren't for loops still considerably faster in most browsers?

Collapse
 
galdin profile image
Galdin Raphael

I was thinking of the same. Found this relevant reddit discussion.

I think this is something browsers could optimize. Or probably they already do.
I wonder if there are any benchmarks around.

Collapse
 
anortef profile image
AdriΓ‘n Norte

"The reason? It makes the code more predictible, safer, deterministic, and a lot easier to maintain when you're used to it."

Can you elaborate why? I have never programmed in a functional way in a serious project so I would like to know the reason behind those affirmations.

Thanks.

Collapse
 
mkwong268 profile image
Mitchell

One of the keys to functional programming is no side effects. So code inside the function shouldn't affect things outside of the function.

Another key of functional programming is that functions should not be affected by things outside of it's scope. (ie: For any given set of parameters the function will always have the same return for that set of parameters).

Keeping these in mind will make code more predictable and safer.

Collapse
 
brunojennrich profile image
bruno jennrich

what a great advice to replace == by ===... NOT!

this will render a lot of code as unfunctional.

Collapse
 
ethan profile image
Ethan Stewart

I would argue that in a lot of cases, code that breaks from changing == with === probably stands in need of some improvement anyway. Just IMHO

Collapse
 
brunojennrich profile image
bruno jennrich

legacy code?

Thread Thread
 
ethan profile image
Ethan Stewart

Valid exception to the rule, but unless you're going to update and change it, you probably don't need to lint legacy code, which was the context in which the original post mentioned replacing == with ===

Collapse
 
themattyg profile image
Matt Graham

Semicolon β€˜till I die.

Collapse
 
maurodaprotis profile image
Mauro Daprotis

Great Post! Love the JS code without the semi-colon. I'm definitely gonna install StandardJS

Collapse
 
gregorgonzalez profile image
Gregor Gonzalez

Nice! It's a really good tool. I'll use it and it's perfect for a collaborative project

Collapse
 
alinp25 profile image
Alin Pisica

Greetings! I'm new to this... How should I code this in a better way? What should I change?

pastebin.com/c6zfhf6F

Collapse
 
amadeot profile image
Amadeo

Fantastic article!

Collapse
 
hawicaesar profile image
HawiCaesar

Great post! I want to take JS code a new level, I guess you have given me something keep in mind a lot.