Understanding the significance of arrow functions

Greetings Ladies and Gents,

Hope everyone is well!

Hopefully a simple question:

  • What are the advantages of using the arrow function over traditional function declaration?

For example in the YT video code challenge the following code was used

 const createPerson = (name, age, gender) => {
  
  return {
   name: name,
   age: age,
   gender: gender
  };
 };

From what I understand so far arrow functions are useful for :

  • Anonymous functions = being able to create and call a function through a variable set through let or const
  • Short hand = more code efficient to write using arrow functions for small, simpler functions with implied return

That’s about as far as I’ve understood, are there any other conveniences I’m unaware of? And is my current understanding correct?

Cheers!

D.W

Most of the time, they are just syntactic sugar. See MDN: Arrow Function Expressions. for some explanation and examples.

The different anonymous function declarations are slightly different and sometimes arrow functions are discourged; see the Mocha documentation, for one example.

1 Like
  • very useful for callbacks methods, because it’s much less verbose.
  • lexical this (it’s picked up from surrounding environment). This helps a lot with objects: it fixes the issue of needing to use var that = this; or bind (and it doesn’t create two functions like bind does) to hold onto the value of this.

https://exploringjs.com/es6/ch_arrow-functions.html#ch_arrow-functions

This isn’t any different to using function declarations (const example = function () {). The const createPerson example doesn’t do anything function createPerson would do either.

2 Likes

Thank you! I appreciate you taking the time to answer this :slight_smile:

Thank you, Dan!

I see, also that website is very helpful!

I was thinking that by being able to assign a function to a const, const example = function () it could be useful in terms of clarity of code, i.e. a commonly used function being “relabelled” to be more relevant to a given section of code

This was helpful, thanks again!

D.W

You would think, but generally no, if you’ve a function that’s used in many places you normally want to just use that function directly under its given name, at least within a single file – you’d likely just be obfuscating things otherwise. If it’s being imported from another file, then there are good reasons for aliasing, but you would alias like:

import { myFunction as aliasedFunction } from "./example.js";

// or if it's a default export, you're aliasing anyway:
import myFunction from "./example.js";
1 Like

I see, I just got onto importing and exporting today haha, thank you!

D.W.

1 Like