Hacker News new | ask | show | jobs
by lolive 3088 days ago
I am not at all a front-end developper. But isn't jQuery the DOM API done right? [Which is a good thing, but only the beginning of the journey.]
2 comments

DOM APIs have much improved since jQuery first arrived, so while that was the case originally, it's become less true over time. It's definitely still less verbose though, for example:

  $('.my-component div').css({ background: 'yellow' })
vs.

  Array.from(document.querySelectorAll('.my-component div')).map(node => {
    node.style.background = 'yellow';
  })
The modern DOM API has forEach on NodeList so you can skip the Array.from.

  document.querySelectorAll('.my-component div').forEach(node => node.style.background = 'yellow');
https://developer.mozilla.org/en-US/docs/Web/API/NodeList/fo...
Why use map instead of forEach?
If you only want to translate(map) each element in to another set of value, using Map is much more simpler and readable than forEach
Actually, this is incorrect. You're abusing map here. The purpose of map is to map an existing array onto a new array. You're using map here to mutate properties on nodes in the original array, and creating a new Array, which has the length of the initial array, where each value is the return value of `node.style.background = 'yellow';`

forEach is much more indicative of what you're actually doing here, which is running through an iterable and mutating properties on each node.

Simple rule of thumb: if you're not using the results of `map`, you shouldn't be using it.

The code loops through an array, has side effects and returns nothing so forEach would be more descriptive IMO.

As for simple/readable it’s the same code but s/map/forEach.

Yes, in a way... it’s certainly (IMO) nicer to use than the DOM API. But “done right” used to mean not just “nicer to use” but “actually implemented correctly” (unlike major browsers at the time). Now that the DOM basics are pretty well-standardized, it’s mostly just “sugar” which isn’t necessarily worth the extra bundle size.

Another, bigger factor is that most modern frameworks use some form of templating and binding which means that you have less need to modify/interact with the DOM directly.