Quantcast
Viewing latest article 5
Browse Latest Browse All 21

JavaScript: Did you know about the comma operator?

return (a, b, …, z)

It will return z, evaluating a, b, ... first. At first it seems not very useful, but consider this example:

const fun = x => x + 1

What if you want to add a console.log call before x + 1 ? With comma operator, adding side-effects to functional expressions is simple:

const fun = x => (console.log (x), x + 1)

And in comparison with…

const fun = x => { console.log (x); return x + 1 }

…it requires fewer modifications.

P.S. you could actually create a wrapper over console.log that returns its first argument:

const fun = x => log (x) + 1

There’s even a library that does that (and much more): Ololog

Image may be NSFW.
Clik here to view.

Viewing latest article 5
Browse Latest Browse All 21

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>