Pokazywanie postów oznaczonych etykietą arrows. Pokaż wszystkie posty
Pokazywanie postów oznaczonych etykietą arrows. Pokaż wszystkie posty

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.

czwartek, 3 września 2015

ES6 - arrows

The biggest difference between arrow and function is this value. Function uses its own this value, but arrow uses this value of the enclosing context.

Arrows are always anonymous functions!

Their syntax is slightly different than function expression:
(args) => { statements }


There could be few variations from this main version:
(arg1, arg2, argN) => { statements }
arg1 => { statements }
() => { statements }

(arg1, arg2, argN) => { statements }
(arg1, arg2, argN) => expression
(arg1, arg2, argN) => ({ prop: val })


It means - prentheses are optional. Mostly if there is only one argument, or only one value to return, this could be simplified.
But there is a catch:
(arg1, arg2, argN) => expression

but
(arg1, arg2, argN) => { return expression }


Example:
(arg1, arg2) => arg1 * arg2

(arg1, arg2) => { return arg1 * arg2 }


Both return the same, but we can write it in different way.