Arrow Functions have a sleek, concise syntax. You can skip braces if you have only one parameter and omit the return statement and curly braces for single expressions.
let explorer = cat => `${cat} in space!` What makes Arrow Functions special is that they do not have their own this.
Letβs see an example. The following code snippet will return undefined.
class Space {
constructor( planet = 'π' ) {
this.spaceObject = planet
}
explore(cats) {
// returns undefined
cats.forEach(function(cat) {
this.spaceObject += cat
})
}
}
let solarSystem = new Space()
solarSystem.explore(['π±', 'π']) This was the workaround used for the issue before Arrow Functions were introduced.
class Space {
constructor( planet = 'π' ) {
this.spaceObject = planet
}
explore(cats) {
// workaround
let that = this
cats.forEach(function(cat) {
that.spaceObject += cat
})
}
}
let solarSystem = new Space()
solarSystem.explore(['π±', 'π']) Life with Arrow Functions is simpler.
class Space {
constructor( planet = 'π' ) {
this.spaceObject = planet
}
explore(cats) {
// arrow function in use
cats.forEach(cat => this.spaceObject += cat)
}
}
let solarSystem = new Space()
solarSystem.explore(['π±', 'π'])