DEV Community

Discussion on: Traditional Functions or Arrow Functions in Javascript?

Collapse
 
edreeseg profile image
Ed Reeseg

I use them pretty interchangeably these days - I like the traditional syntax for how self-explanatory it is (though, these days, I think most people are just as familiar with ES6 arrow syntax).

As Ben mentioned previously, one of the main draws of arrow syntax has to do with how it interacts with the this keyword. It does not generate its own context for this, but rather inherits the context of the environment in which it was created.

For things like React class components, this can be a godsend.

class Test extends React.Component {
  constructor(props){
    this.log = this.log.bind(this);
  }
  log(){
    console.log(this);
  }
  render(){
    return // Whatever
  }
}

vs.

class Test extends React.Component {
  log = () => console.log(this);
  render(){
    return // Whatever
  }
}

Of course, with more people being familiar with the convenience of Hooks, this is a bit less relevant. Still good to note.

Collapse
 
jharteaga profile image
Jose Arteaga

Right! I was reading more about it and I found what you mentioned about the this keyword. I'm not familiar yet with this concept, but I will read up on it. For sure there should be an advantage using the arrow syntax. Thanks Ed!