Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
In this video we'll cover the basic syntax for arrow functions.
Benefits of Arrow Functions
The first benefit of arrow functions, as discussed in this workshop, is it's shorter syntax.
const sayHello = () => {
console.log("Hello");
}
The advanced technical benefit with arrow functions comes with using callbacks in object orientated programming and using this
.
In this example we're increasing a person's age by 1 ever one second.
function Person() {
this.age = 0;
var self = this;
setInterval(function() {
self.age ++;
}, 1000);
}
You have to assign this
to a variable, in this case self
because whenever you create a function a new this
value is defined.
Arrow functions do not have a this
value defined. You can write the above code in the following way.
function Person() {
this.age = 0;
setInterval(() => {
this.age ++;
}, 1000);
}
Not worrying about this
in your code is less frustrating. For more reading check the MDN documentation on Arrow Functions
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up