Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jlrdw's avatar
Level 75

Arrow functions

I've used javascript for years, but fairly new to the arrow functions.

Can someone tell me how this:

const getData = async () => {
    //rest of code

28 spaces used to reach {

is better than this:

async function getData() {
   // rest of code

25 spaces to reach {

So it sure is not shorter.

I ask because so far some of the newer shortcuts just don't make sense to me.

One of the arguments for them:

Arrow functions are often preferred in modern JavaScript code for their readability and shorter syntax

In the above the old way is very readable and shorter?

I also notice even modern Axios JS uses the old style in the example:

async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

See https://axios-http.com/docs/example

I wish folks would learn:

If it ain't broke don't fix it.

0 likes
5 replies
Tray2's avatar
Tray2
Best Answer
Level 73

In my world it isn't. I much prefer to write my functions in the classic style.

function myFunction() {
}

async function myAsyncFunction() {
}

async function doFunction() {
	await myAsyncFunction();
    myFunction();
}
1 like
MohamedTammam's avatar

In most cases they're same. Sure they're both called function.

The biggest different is when using with objects. Arrow function doesn't have its own this context.

Examples from MDN:

"use strict";

const obj = {
  i: 10,
  b: () => console.log(this.i, this),
  c() {
    console.log(this.i, this);
  },
};

obj.b(); // logs undefined, Window { /* … */ } (or the global object)
obj.c(); // logs 10, Object { /* … */ }
class C {
  a = 1;
  autoBoundMethod = () => {
    console.log(this.a);
  };
}

const c = new C();
c.autoBoundMethod(); // 1
const { autoBoundMethod } = c;
autoBoundMethod(); // 1
// If it were a normal method, it should be undefined in this case

This is really important when using with frameworks that's using classes/objects like Vue or React. And with libraries that's using callbacks. It's really important to distinguish which to use in these cases.

1 like
JussiMannisto's avatar

Arrow notation is just more concise in a lot of cases. Let's say you want to get all verified users from an array of users:

// With arrow:
const verifiedUsers = users.filter(user => user.verified);

// Without arrow:
const verifiedUsers = users.filter(function(user) {
	return user.verified;
});
1 like

Please or to participate in this conversation.