New Functions vs. Old function format

So recently I’ve been doing my Introduction to Javascript course, and in ES6, instead of using:

function functionName(params) {

you use:

const functionName = (params) => {

There isn’t a huge difference, but what makes the second function format better than the first?

1 Like

Not better, just simpler. It is not a magic pill. The standard form is still a necessity if we wish to access the objects this and arguments.

Arrow syntax is meant for use in a more functional sense with smaller, pure functions that do one thing, and one thing only. They are super handy as callbacks and predicate functions since the syntax rules are somewhat relaxed.

  • no parens on single parameter
  • no block braces when only a single statement
  • implicit return when only a single statement
const is_int = x => ! (x % 1)

The above is a predicate function that returns true if there is no decimal fraction. We can parse the integer out of the number without changing its value.

Arrow functions cannot be used as methods but ES6 gives us new syntax for them which is also simpler.

obj = {
  prop: value,
  print () {
obj.print()    // value

Above it is not obvious why arrow functions won’t work here. Notice the this? That’s why.

Couple other things about arrow functions…

  • When we have no parameter, or multiple parameters the parens are mandatory.

  • When there is more than one statement, curly braces are mandatory.

  • When there are curly braces, return is mandatory.


Ahhh ok that makes sense.

I was wondering about that actually, but that makes sense.