sobota, 30 maja 2020

Function vs arrow function

Arrow function came in 2015 together with new ECMAScript 5. It was a revolution! No more var that = this; to be able to use parent context in a callback.

I really enjoyed this time and like others was using arrow functions everywhere. But 5 years later I started to hate arrow functions used as normal functions.

Code with one-liner functions and other variables:
const getData = dataKey => get(state, dataKey);
const makePlainObj = () => ({});
const doSth = ({ a, b }) => {console.log(b)};
const abc = { get: someFn };


Code with normal functions:
function getData(dataKey) {
  return get(state, dataKey);
}

function makePlainObj() {
  return {};
}

function doSth({ a, b }) {
  console.log(b);
}

const abc = { get: someFn };

Yes, second code is longer but at the same time much more readable. On first look it is visible what is a variable and what is a function. Also functions are hoisted when created as variables arrow functions are not.

Brak komentarzy:

Prześlij komentarz