This post is a bit weird for me to write because I basically only write arrow functions. I rarely ever use the traditional function
syntax anymore. However, this post is still worth writing because many of my students only use the function
syntax and I want to both show them another way and point out the minor differences that come with arrow functions!
First, what am I talking about? Well! Glad you asked, let me show you below. As you can see I have declared two very simple functions in two different ways. The bottom one is an arrow function.
Ooooh, how fancy.
An arrow function is a function declared using the =>
syntax. Get it? It looks like an arrow.
function someFunc() {
console.log('No Me Gusta')
}
const otherFunc = () => console.log('Me Gusta')
They really come in handy when using higher-order function like map
, which you can read all about in this Blog Post
someArray.map(function(item) {
return item * 2
}) // Eww gross.
someArray.map(item => item * 2) // Sexy!
See how much better the arrow function looks there? I am a big fan of simplicity and minimal syntax. I believe that comes from writing so much Ruby in my early days of programming, and arrow functions deliver big on simplicity.
One of the first things worth taking note of about arrow functions is that when the expression is on a single line the {}
braces are not necessary. As you can see in all of the examples above. The return
is also implicit for this single line functions. How cool!
This doesn't mean every arrow function has to be a single line though. As I stated above, I always use the arrow syntax, which means my multi-line functions look like this.
const someNewFunction = (arg1, arg2) => {
// Do some stuff with arg1
// Do some other stuff with arg2
// Solve world hunger
return arg1 + arg2
}
Notice we need the return
again when it is multiple lines.
One other thing worth noting before I wrap this really short post is that the context of this
is different for arrow functions. Basically, this
works lexically for arrow functions. Meaning the way you thought this
worked originally only to learn you had no clue how this
actually works at all. It keeps the context from where it was declared, kind of like self in any OO language. Which means you can do this in React without having to worry about binding.
class App extends React.Component {
constructor(props) {
super(props)
this.state = { count: 0 }
}
increase = () => this.setState({ count: this.state.count + 1 })
render() {
return (
<div className="App">
<button onClick={this.increase} />
<h2>{this.state.count}</h2>
</div>
)
}
}
Top comments (2)
The link to the blog post about map isn't working (404 error).
Oh snap you are right. Bad copy paste job.
lvrbrtsn.com/blog/how-the-hell-do-...
I'll fix the post too.